Overview of Constraint Validation in JavaScript
Let’s overview how to add constraint validation to our JavaScript application.
We'll cover the following
Adding constraint validation to the application
The minimal JavaScript front-end web application that we’ve discussed in Building a Minimal Web App with Plain JS in Seven Steps has been limited to support the minimum functionality of a data management application only. For instance, it did not prevent the user from entering invalid data into the application’s database. In this chapter, we’re going to look at how to express integrity constraints in a JavaScript model class, and how to perform constraint validation both in the model part of the application and in the user interface built with HTML5.
Since using the
new HTML5 input
field types and validation attributes (like required
, min
, max
, and pattern
)
implies defining constraints in the UI, they’re not really useful in a best-practice approach where constraints
are only checked, but not defined, in the UI.
Consequently, we’re not going touse the new HTML5 features for defining constraints in the UI. Instead we’ll use two methods of the HTML5 form validation API:
-
setCustomValidity
: This allows marking a form field as either valid or invalid by assigning either an empty string or a non-empty (constraint violation) message string. -
checkValidity
: This is invoked on a form before user input data is committed or saved (for instance, with a form submission). It tests if all fields have a valid value.
In the case of two special kinds of attributes that have calendar dates or colors as values, it’s desirable to use the new UI widgets defined by HTML5 for picking a date or picking a color (with corresponding input
field types).
Create a free account to view this lesson.
By signing up, you agree to Educative's Terms of Service and Privacy Policy