Add custom validation and create bubbling invalid and valid events to form elements.
new Validator( HTMLFormElement, Object )
Create a new validator instance.
HTMLFormElement- the form to validateObject- the validator parameters
The parameter Object contains one entry to pass custom validation rules:
customRules- Array of custom validation rules
constparameters={customRules: [ ... ]}A custom validation rule is an object containing two entries:
match: A CSS selector matching the elements that you want the validator to testtest: A function that will test the elementmessage: An error message to pass when the test fails (optional)
The test function must return true, false, or a custom ValidityState you want to return for this test. If the return value is false the ValidityState value will be customError. When true the test succeed, otherwise it fails.
[{// apply maxlength tests to all inputs, not only [type=number]// the ValidityState value will return "tooLong" if the test failsmatch: '[data-maxlength], [maxlength]',message: 'Too many characters',test: (el)=>{constlength=parseInt(el.dataset.maxlength||el.getAttribute('maxlength'),10);returnel.value.length<=length ? true : 'tooLong';}},{// the ValidityState value will return "customError" if the test failsmatch: '[data-match]',test: (el)=>{constshouldMatch=document.getElementById(el.dataset.match);returnshouldMatch&&shouldMatch.value===el.value;}}]importValidatorfrom'@switch-company/form-validation';constparams={
customRules[{match: '[data-maxlength], [maxlength]',message: 'Too many characters',test: (el)=>{constlength=parseInt(el.dataset.maxlength||el.getAttribute('maxlength'),10);returnel.value.length<=length ? true : 'tooLong';}},{match: '[data-match]',test: (el)=>{constshouldMatch=document.getElementById(el.dataset.match);returnshouldMatch&&shouldMatch.value===el.value;}}]};constvalidator=newValidator(document.querySelector('form'),params);validator.checkValidity();// returns `true` or `false`Check the validity of the passed element. Defaults to the form element the validator was created on if no HTMLElement is passed.
Return true when valid, otherwise false.
constvalidator=newValidator(document.querySelector('form'));validator.checkValidity();// returns `true` or `false` depending of the `form` validity statevalidator.checkValidity(document.querySelector('fieldset'));// returns `true` or `false` depending of the `fieldset` validity statevalidator.checkValidity(document.querySelector('input'));// returns `true` or `false` depending of the `input` validity stateSet custom error messages on the form elements by passing an object with [element name]: 'error message'. Remove all custom errors by calling it without passing anything. Usually this method is used if the backend respond with some extra errors that the front-end can't or won't handle. For custom front-end errors, use custom rules by passing them when instanciating the constructor.
constform=document.querySelector('form');constvalidator=newValidator(form);if(validator.checkValidity()){// post the data if front-end doesn't see any errorsconstbackendResponse=awaitfetch('/endpoint',{method: 'POST',body: newFormData(form),}).then(r=>r.json());/* * errors object should look like this: * { * 'postal-code': 'Cannot deliver to this postal code' * } */if(backendResponse.errors){// trigger an invalid event to the listed form elementsvalidator.setValidity(backendResponse.errors);}}Return the validator instance of a fieldset contained in the form. This allows you to check the validity of the fieldset.
constvalidator=newValidator(document.querySelector('form'));constfieldsetValidator=validator.fieldset(document.querySelector('fieldset'));fieldsetValidator.checkValidity();// returns `true` or `false`Return an Array of invalid fields. .checkValidity() must be called before or the property won't reflect the validity state of the form.
constvalidator=newValidator(document.querySelector('form'));validator.checkValidity();validator.invalid;// returns an `Array` of invalid fieldsReturn an Array of validators instances created on the fieldsets elements contained in the form.
constvalidator=newValidator(document.querySelector('form'));validator.fieldsets;// returns an `Array` of validatorsEvents invalid and valid are created with the CustomEvent constructor and set to bubble so there's no need to parse and bind every field. The current validityState of the field is passed in the detail object of the event.
An invalid event is dispatched to any field failing to validate.
constform=document.querySelector('form');form.addEventListener('invalid',e=>{console.log(e.target);// return the fieldconsole.log(e.detail.validityState);// return the current validityState of the fieldconsole.log(e.detail.message);// return the message set by the custom rule or the `.setValidity()` methodconsole.log(e.detail.wasInvalid);// return `true` if the field was invalid before calling `.checkValidity()`, `false` otherwiseconsole.log(e.detail.context);// return the HTMLElement passed to the `.checkValidity()` method or HTMLElement bond to the validator});A valid event is dispatched to any field passing the validation.
constform=document.querySelector('form');form.addEventListener('valid',e=>{console.log(e.target);// return the fieldconsole.log(e.detail.validityState);// return the current validityState of the fieldconsole.log(e.detail.wasInvalid);// return `true` if the field was invalid before calling `.checkValidity()`, `false` otherwiseconsole.log(e.detail.context);// return the HTMLElement passed to the `.checkValidity()` method or HTMLElement bond to the validator});