import validation from 'dataparcels/validation';
import validation from 'react-dataparcels/validation';
Dataparcels' validation plugin provides an easy way to test whether data conforms to a set of validation rules. This is most useful when checking if user input is correct before allowing changes to be submitted.
Once configured, it provides function that can be run against Parcel data, and it will set Parcel meta wherever data is invalid, and also block any submit()
actions unless all data is valid.
Please refer to the UI Behaviour page to see a full example.
let [parcel, parcelControl] = useParcelForm({
value,
beforeChange: () => validation({
'name': value => value ? null : `Name must not be blank`,
'animals.*.type': value => value ? null : `Animal type must not be blank`,
'animals.*.amount': [
value => Number.isInteger(value) ? null : `Animal type must be a whole number`,
value => value >= 0 ? null : `Animal type must be positive`
]
})
// ^ run validator before data updates
});
// parcel.get('name').meta.invalid will contain `Name must not be blank` if it is blank, or null otherwise
// parcel.meta.valid will contain true if all validation rules pass, or false otherwise
// parcelControl.submit() will only work if all validation rules pass
validation(validationRuleMap: ValidationRuleMap) => ParcelUpdater;
type ValidationRuleMap = {
[matchPath: string]: ValidationRule|ValidationRule[]
};
type ValidationRule = (value: any, keyPath: Array<number|string>, topLevelValue: any) => any;
The validation
function requires a single argument, a validation rule map.
Match paths are strings that indicate which parts of the Parcel's data shape to run the associated validation rule(s) against. Dots (.
) indicate nested properties, and asterisks (*
) indicate wildcards.
name
matches a property called name
animals.*
matches all elements of a property called animals
animals.*.type
matches all properties called type
on all elements of a property called animals
Validation rules are functions that should return something if the data being validates is invalid. Usually this is a string describing why the data is invalid, which can be rendered in the form.
If the data is valid, null
should be returned.
The validation
function returns a ParcelUpdater
function, which is most suitable to be passed into useParcelForm.beforeUpdate, useParcelBuffer.beforeUpdate or useParcelState.beforeUpdate.
This returned function is often used with useParcelForm.
This validation plugin sets the following meta:
An example of how this meta can be used can be found here.