Introduction to Constraint validation API

Form validation is one of the most common tasks you can face with as a frontend developer. If your project runs on React or other popular framework, you can choose tools like Formik or Redux-form for validation. But if your website does not use external tools, you can struggle from some difficult moments of validation forms with vanilla technologies.
In this little article we will take a look at really powerful API. It exists in almost every browser and allows you to validate forms without any problems — Constraint validation API.
We will create a small form with different types of fields and will see that validate forms with this API is much easier than writing some bicycles.
First of all — let`s create the basic form with a few fields of diffrent types.
We have a common text input for username and email field. Also we can add images as an avatar and a phone number.
Let`s define some validation rules for this form.
- Username is required and should be at least 3 characters length.
- Email field is required and should be valid (obvious 🙃).
- Avatar is required.
- Phone number field is also required and should pass check for this phone number mask.
These rules can be easily implemented with Pure HTML and we should only check validity of form with JavaScript. We will use input HTML attributes which specifies value of the input.
You can check all input validation attributes here.
Now we can add some JS code to check validity of form while submitting it and it will be really short.
Note: We can use form.checkValidity()
for the whole form, and also check validity of certain fields and its rules.
Thats all! Our form will validate most of the cases.
We can add more strict validations for email for example, add this Regular expression and check it every time on submitting.
You can check live demo on CodePen.
Additional resources:
Written by Kletskov Gleb, frontend software engineer in Mail.ru Group.