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

Table of Contents

1. Introduction
2. New Issues
3. Using ES6 Modules
4. Make a JavaScript Class Model
5. Set up the Folder Structure
5.1. Provide utility functions and error classes in library files
5.2. Create a start page
6. Write the Model Code
6.1. Summary
6.2. Code the model class as a constructor function
6.3. Code the property checks
6.4. Code the property setters
6.5. Add a serialization function
6.6. Data management operations
7. Write the View Code
7.1. Set up the user interface for Create Book
7.2. Set up the user interface for Update Book
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
9.3. Improving the user experience by showing helpful auto-complete suggestions
10. Quiz Questions
10.1. Question 1: Methods to add in JS class model
10.2. Question 2: Implementing constraints
10.3. Question 3: Implementing setter methods
11. Practice Projects
11.1. Project 1 - Validate movie data
11.2. Project 2 - Validate country data

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 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 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).