Reforml
GitHub

Validation

Reforml provides way to utilize HTML constraints and any custom validators including validators from other libraries. You can also customize the error message

HTML Constraints

You can directly supply HTML constraints in field definition, if you are using controlled form, you need to manually called validate in onChange handler since HTML constraints are only validated in uncontrolled form

Live Demo
value:
{}

OK

Custom Validation

By supplying a validatorDictionary to ReformlProvider, BasicForm inside it can use yaml with field containing a validation property. The validation property is a list of "validation rule name" or "rule name to params array map" or "rule name to single param" You can notice the mapping of params in YAML definition to validator function implementation

validatorDictionary is a rule name to validator map, a validator is a function that accept first parameter as the field value, rest parameter from field validation settings from the yaml, and return a boolean to determine whether the value passes the validation.

Live Demo
value:
{}

OK

In field definition you can even implement a validator function directly

Live Demo
value:
{}

OK

validator.js integration

The Validators used in reforml shares the same interface as validator.js, so you can use them directly

npm i validator
import validators from 'validator'
const myValidators = {
isFoo: (value) => value === 'Foo',
isEqual: (value, compare) => value === compare,
isLengthBetween: (value, a, b) => value.length >= a && value.length <= b
}
() => {
return <ReformlProvider validatorDictionary={{
...validators,
...myValidators
}}>
{/* BaseForm here */}
</Reforml>
}

Customize the error message

ValidateErrorFormatter has the following signature

export type ValidateErrorFormatter = <T>(value: T, ruleName: string, params: never[]) => string

value is the value supplied in the form, ruleName is the name of validation, params is the array of param supply to the validator

and you can supply the formatter to ReformlProvider

const validateErrorFormatter = (_, ruleName, params) => {
return ruleName + (params.length === 0 ? '' : ':' + params.join(','))
}
() => {
return <ReformlProvider validateErrorFormatter={validateErrorFormatter}>
{/* BaseForm here */}
</ReformlProvider>
}
Previous:
Reduce Fields
Next:
Show If