Chapter 8. Implementing Constraint Validation in a Plain JS Web App

Table of Contents

1. Introduction
2. New Issues
3. Make a JavaScript Class Model
4. Set up the Folder Structure Adding Some Library Files
4.1. Provide general utility functions and JavaScript fixes in library files
4.2. Create a start page
5. Write the Model Code
5.1. Summary
5.2. Code the model class as a constructor function
5.3. Code the property checks
5.4. Code the property setters
5.5. Add a serialization function
5.6. Data management operations
6. Write the View Code
6.1. The data management UI pages
6.2. Initialize the app
6.3. Set up the user interface
7. Run the App and Get the Code
8. Possible Variations and Extensions
8.1. Adding an object-level validation function
8.2. Using implicit JS setters
9. Points of Attention
9.1. Boilerplate code
9.2. Configuring the UI for preventing invalid user input
10. Practice Projects
10.1. Project 1 - Validate movie data
10.2. Project 2 - Validate country data
11. Quiz Questions
11.1. Question 1: Validation in setter (1)
11.2. Question 2: Validation in setter (2)
11.3. Question 3: Methods to add in JS class model
11.4. Question 4: Implementing constraints

1. Introduction

The minimal JavaScript front-end web application that we have discussed in Chapter 3 has been limited to support the minimum functionality of a data management app only. For instance, it did not take care of preventing the user from entering invalid data into the app's database. In this chapter, we show how to express integrity constraints in a JavaScript model class, and how to perform constraint validation both in the model part of the app and in the user interface built with HTML5.

We show how to perform responsive validation with the HTML5 form validation API. Since using the new HTML5 input field types and validation attributes (like required, min, max and pattern) implies defining constraints in the UI, they are not really useful in a best-practice approach where constraints are only checked, but not defined, in the UI.

Consequently, we will not use the new HTML5 features for defining constraints in the UI, but only use two methods of the HTML5 form validation API:

  1. setCustomValidity, which allows to mark a form field as either valid or invalid by assigning either an empty string or a non-empty (constraint violation) message string;

  2. checkValidity, which 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, having calendar dates or colors as values, it is desirable to use the new UI widgets defined by HTML5 for picking a date or picking a color (with corresponding input field types). Unfortunately, in 2017, the HTML5 date picker widget is still not supported by all major browsers.