Using a package for validation
Having demonstrated how server-side and client-side form validation works, it is time to replace the custom checks with those provided by a well-tested and comprehensive validation library.
As with most areas of JavaScript functionality, there are many libraries available, and the one I have chosen for this chapter, validator.js
, is simple and effective and can be used for both client- and server-side validation. Run the commands shown in Listing 11.30 in the part2app
folder to install the packages.
Listing 11.30: Installing a validation package
npm install validator@13.11.0
npm install --save-dev @types/validator@13.11.5
Listing 11.31 updates the client-side validation code to use the tests provided by the validator.js
package.
Listing 11.31: Using a validation package in the client_validation.js file in the src/client folder
import validator from "validator";
export const validate = (propName, formdata) => {
...