--- tags: zeta-dom-react --- # Validators It may be more convenient to have validator factory that intake parameters and returns a validation callback: ```typescript export function pattern(pattern: string) { return (value: string) => { return new RegExp(`^${pattern}$`).test(value) ? '' : 'Invalid pattern'; }; } <TextField onValidate={combineValidators(required, pattern('\\d'))}> ``` ## Combining validators The returning value for validation success or failure makes it very easy to chain validations: ```typescript function required() { return (value: string) => value ? '' : 'Value required'; } function minLength(len: number) { return (value: string) => value.length >= len ? '' : 'Too short'; } <TextField onValidate={combineValidators(required(), minLength(10))} /> ``` ## Parameterizing validations By validator factory and combining validators, it will be easy to parameterize common validations: ```typescript interface TextFieldProps extends FormFieldProps<string> { required?: boolean; maxLength?: number; pattern?: string; } function TextField(props: TextFieldProps) { props = { ...props, onValidate: combineValidators( props.required && validator.required(), props.maxLength && validator.maxLength(props.maxLength), props.pattern && validator.pattern(props.pattern), props.onValidate ) } const { value, error } = useFormField(props, ''); /* ... */ } ``` That consumer can simply do: ```typescript <TextField required minLength="10" pattern="\\d+" /> ```