import * as React from 'react' ; import { isEmail , isEmpty , isInt } from 'validator' ; const validators = { numeric : { message : ( ) => 'This is a numeric field.' , isValid : ( value ) => isInt ( value , { min : 0 } ) , } , email : { message : ( ) => 'Please enter a valid email address.' , isValid : ( value ) => isEmpty ( value ) || isEmail ( value ) , } , required : { message : ( ) => 'This field is required.' , isValid : ( value ) => ! isEmpty ( value ) , } , } ; const stripTags = ( value ) => value . replace ( /(<([^>]+)>)|(\`)|(\*)/gi , '' ) ; const handleState = ( component , currentValidator , value , isDisabled ) => { if ( ! isDisabled && currentValidator ) { const message = validators [ currentValidator ] . message ( ) ; component . setState ( { value , message , isValid : false , } ) ; } else { component . setState ( { value , message : '' , isValid : true , } ) ; } } ; export const validateInput = ( val , component , isDisabled = false ) => { const value = val === undefined || val === null ? '' : String ( stripTags ( val ) ) ; const validation = component . props . validation ; if ( validation ) { const currentValidator = validation . find ( ( item ) => { if ( ! validators [ item ] ) { console . error ( 'Invalid validator <"' + item + '">' ) ; return false ; } return ! validators [ item ] . isValid ( value ) ; } ) ; handleState ( component , currentValidator , value , isDisabled ) ; } } ;