Useful JavaScript functions for manipulating and validating forms using HTML5 client-side form validation.
It could be used with libraries like React.js and Vue.js since they don’t have built-in features for form validation.
Different API used in this file are :
target.checkValidity(), target.validity.validfor checking if there are any errors and gettingvalidityStateobject. The main difference is that checkValidity() will also fire an “invalid” event. If you just want to know whether the value is valid, use ValidityState.valid. But if you want to change the form state to invalid, use checkValidity().validityState.valueMissingto check forrequiredHTLM5 attribute.typeMismatch, patternMismatchfor HTML5 input types andpatternattribute (e.g. regex).tooLong, tooShort, rangeUnderflow, rangeOverflow, stepMismatch, badInputrespectively formaxlength, minlength, min, max, stepattributes (step is fornumbertype) and convert issues (browser, etc.).
Show error messages :
Before sharing the gist link, i would show how it’s possible to check if an input is in invalid state without getting the validityState object. This i very useful when you only and quickly want to show error messages for inputs. You can always use state object for last validation before posting a request.
For this you can bind an event listener to your <input> for the “invalid” event (or to <form>, or any other wrapper if you would avoid adding multiple event listeners) and react to that in your callback function by adding for example a css class. Note that this event is fired after check done on blur and you can lean more about it here.
Github gist :
