@springernature/form-validation
v0.0.3
Published
Javascript module for client-side form validation with custom validation
Downloads
92
Maintainers
Keywords
Readme
np# Form Validation Library
This is a javascript utility for setting up client-side form validation. It makes use of the Constrain Validation API and the associated HTML attributes, It provides a custom error message using the elements eds-c-error component
Custom error messages and custom validation functions can be specified using data attributes
To set up validation import the library and set up a configuration object with custom values:
import createValidatorLibrary from '@springernature/form-validation';
const validator = createValidatorLibrary({
errorMessages: { required: 'This field is required.' },
errorTemplateSelector: '#error-message-template'
});To add client side validation to all forms on the page include the following on document ready:
validator.trackAndValidateForms();
Configuration values
errorTemplateSelector: Here you can define a selector for your error messages.
errorMessages: custom error messages for the following HTML validation types: required, minimumLength, maximumLength, badInput, typeMismatch. Here you can also add error messages for any custom validation functions you have added or the two custom validation functions included with the library: 'forbidTrailingWhitespace' and 'isEqualToField'.
customValidators: This defines custom validation function, the name must match with a data attribute and a custom error message defined in 'errorMessages'.
For example:
const validator = createValidatorLibrary({
errorTemplateSelector: '#error-message-template',
errorMessages: {
isDoiStartsWithTen: 'Your DOI must begin with 10',
isValidDoi: 'Your DOI must be in correct syntax'
},
customValidators: {
isDoiStartsWithTen: (input) => {
const doiPattern = /^10/;
return doiPattern.test(input.value);
},
isValidDoi: (input) => {
const doiPattern = /^10.\d{4,9}\/[-._;()/:A-Z0-9]+$/i;
return doiPattern.test(input.value);
}
});A custom data attribute should then be added to any form input that you wish to validate against this custom function so for the example above:
<input type="text" value="" data-validation-is-doi-starts-with-ten data-validation-is-valid-doi> </input> 