Synchronous validation for redux-form using object schemas.
npm install redux-form-sync-validationvalidate function automatically returns errors in a format that redux-form understands.yarn add redux-form-sync-validationnpm install redux-form-sync-validation --savejs
// model.js
// @flow
import Schema from 'redux-form-sync-validation'export const schema = Schema.object({
key1: Schema.string().min(5).required(),
key2: Schema.boolean().required().valid(true)
})
`
And then use the schema with the validate function provided.
`js
// Form.jsx
// @flow
import * as React from 'react'
import { reduxForm, Field } from 'redux-form'
import type { FormProps } from 'redux-form'
import { validate } from 'redux-form-sync-validation'import { schema } from './model'
class Form extends React.Component {
render() {
const { handleSubmit } = this.props
return (
)
}
}
export default reduxForm({
form: 'FormName',
validate: validate(schema),
})(Form)
`Extensions
It may become necessary for you to add extra validations such as for postcodes or phone numbers. You can extend an existing schema with a new class. You can also make a new schema from the base Schema class obtained by importing the named import import Schema, { Schema as BaseSchema } from 'redux-form-sync-validation', not to be confused with the default export. You can then use the helpful extend function which takes the default export and then an object with a set of key value pairs to override on that object. These keys can be existing keys or new keys.You can add new validation rules using the
addRule method which takes a function of the form type ValidationRule where type ValidationResult = { isSuccess: boolean, error: ErrorObject }. The StringSchema also has the helpful match method for matching against regex patterns.`js
import Schema, { extend, StringSchema } from 'redux-form-sync-validation'
import type { ValidationRule } from 'redux-form-sync-validation'
import { UK_PHONE_NUMBER_REGEX, PASSWORD_REGEX, isValidPostcode } from '../../constants'class ExtendedStringSchema extends StringSchema {
UKPhone(): this {
return this.match(UK_PHONE_NUMBER_REGEX, 'invalid UK phone number')
}
postcode(): this {
return this.addRule(value => ({
isSuccess: !value || isValidPostcode(value),
error: 'invalid postcode'
}))
}
password(): this {
return this.match(PASSWORD_REGEX, PASSWORD_MESSAGE)
}
}
const newSchemaObject = extend(Schema, { string: ExtendedStringSchema })
export default newSchemaObject
`
This would then allow you to import your new schema object and use it as Schema.string().postcode().required()`