In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In a certain input field, only valid hexadecimal color codes strings are allowed. We can also validate these input fields to only accept valid hexadecimal color codes strings using express-validator middleware.
Command to install express-validator:
npm install express-validator
Steps to use express-validator to implement the logic:
Install express-validator middleware.
Create a validator.js file to code all the validation logic.
Validate input by validateInputField: check(input field name) and chain on validation isHexColorl() with ‘ . ‘
Use the validation name(validateInputField) in the routes as a middleware as an array of validations.
Destructure ‘validationResult’ function from express-validator to use it to find any errors.
If error occurs redirect to the same page passing the error information.
If error list is empty, give access to the user for the subsequent request.
Note: Here we use local or custom database to implement the logic, the same steps can be followed to implement the logic in a regular database like MongoDB or MySql.
Example: This example illustrates how to validate an input field to only allow valid hexadecimal color code.
Please Login to comment...