react-vld v4.1.4
react-vld
Simple and flexible validation for React components.
The main thing here is
Validatorcomponent. Use it as a wrapper for your input components, forms, or whatever component you want to validate.Validatoracceptschildrenprop as a function and passes the validation state as a parameter into it.For updating validation state
Validatoruses a functional prop -rule. If aValidationErrorwas thrown within therule, then validation fails, and theValidatorupdates validation state.By default,
Validatoris rerendered every time the validation state is updated.You can nest
Validatorcomponents. The parentValidatorfails when any of the childValidatorfails.
Installation
npm i react-vldUsage
Example of Input component
import { Validator, ValidationError } from 'react-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'
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>
)API
Validator props
rule()used to calculate new validation statemapError(validationError)transforms validation error, may be useful for adding some payload to the errorchildren(validationState)
validationState has the following structure
validate({ updateComponent = true } = {})invokes validation routine (callingruleand also callingvalidatefor every childValidator)resetValidation({ updateComponent = true } = {})resets validation state (also callingresetValidationfor every childValidator)isValid=true|false|undefinedisInvalid=true|false|undefinedvalidationError=ValidationError|undefined
ValidationError
constructor(message, payload)
License
MIT
5 years ago
5 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago