How to validate if input in input field has ASCII characters using express-validator ?
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 Ascii characters are allowed i.e. there is not allowed any Non-ASCII characters (Ex: ñ). We can also validate these input fields to accept only ASCII characters 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 the validation isAscii() 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 accept only ascii characters.
Filename – index.js
Filename – repository.js: This file contains all the logic to create a local database and interact with it.
Filename – form.js: This file contains logic to show the form to submit Ascii text.
Filename – validator.js: This file contain all the validation logic(Logic to validate a input field to accept only ascii characters).
Filename – package.json
Database after successful form submission:
Note: We have used some Bulma classes(CSS framework) in the signup.js file to design the content.