Simple and flexible validation for React and Preact components.
-
The main thing here is
Validator
component. Use it as a wrapper for your input components, forms, or whatever component you want to validate. -
Validator
acceptschildren
prop as a function and passes the validation state as a parameter into it. -
For updating validation state
Validator
uses a functional prop -rule
. If aValidationError
was thrown within therule
, then validation fails, and theValidator
updates validation state. -
By default,
Validator
is rerendered every time the validation state is updated. -
You can nest
Validator
components. The parentValidator
fails when any of the childValidator
fails.
For React
npm i react-vld
For Preact
npm i preact-vld
Example of Input component
import { Validator, ValidationError } from 'react-vld' // or from 'preact-vld'
export default () => {
const [value, setValue] = useState('')
const checkValue = useCallback(() => {
if (value.trim() === '') {
throw new ValidationError('Required field')
}
}, [value])
const handleChange = useCallback((ev) => {
setValue(ev.target.value)
}, [])
return (
<Validator rule={checkValue}>
{ ({ validate, isInvalid, validationError }) => (
<Fragment>
<input
value={value}
onBlur={validate}
onChange={handleChange}
/>
{ isInvalid && (
<div>
{ validationError.message }
</div>
) }
</Fragment>
) }
</Validator>
)
}
Example of Form component (nesting)
import { Validator, ValidationError } from 'react-vld' // or from 'preact-vld'
export default () => (
<Validator>
{ ({ validate }) => {
const handleSubmit = useCallback((ev) => {
ev.preventDefault()
if (validate().isValid) {
alert('Submitted!')
}
}, [validate])
return (
<form onSubmit={handleSubmit}>
<Input />
<button type="submit" />
</form>
)
} }
</Validator>
)
-
rule()
used to calculate new validation state -
mapError(validationError)
transforms validation error, may be useful for adding some payload to the error -
children(validationState)
-
validate({ updateComponent = true } = {})
invokes validation routine (callingrule
and also callingvalidate
for every childValidator
) -
resetValidation({ updateComponent = true } = {})
resets validation state (also callingresetValidation
for every childValidator
) -
isValid
=true|false|undefined
-
isInvalid
=true|false|undefined
-
validationError
=ValidationError|undefined
constructor(message, payload)
MIT