NodeJs Tutorials
- NodeJs
- Install NodeJs
- Why use NodeJs
- NodeJs Process Model
- create First Application
- Run NodeJs Application
- Node.js Console
- Node.Js Modules
- URL Modules
- node.js Callback
- Node.js Events
- Upload Files
- Upload single & Multiple Files
- NodeJs File System
- NodeJs Email
- Debugging NodeJs
- .ENV
- NodeJs Mysql
- Helpers
- encription and decription in nodeJs
- Query string
- Date & Time
- Express Js
- Template Engine with Express
- MVC Pattern in Node.Js
- list of NPM Module
- Middleware
- Body Parser
- Render
- Nodemon module
- Morgan module
- Flash Message in ExpressJs
- Session
- Session store in database
- Cookies
- Helmet
- Multer
- Router: How To Use Routing In Node.Js
- App.Js
- express.json() and express.urlencoded()
- REST APIs in NodeJs
- Gloabal Objects
- Submit Form Data
- How to get Post Data in Node.js
- How to Get URL Parameters in Node.js
- How to create Node Project
- How to Insert Form Data Into the MySql Table Using Node.js
- How to fetch Data from MySQL database table using Node.js
- CRUD Example
- Await and Async
- Promises
- Login Example
- Password Encription
- How to validate Form (Form Validation) in Node.Js?
- Registration & Login form usingn Node.Js & MySql?
- Forgot & Reset Password
- File Upload in Node.Js with ExpressJs
- Resize Image Before Upload using Multer Sharp
- Upload multiple file using node.js with multer module
- Upload file using node.js with multer module
- Client IP Address
- REST API Downloading File in NodeJs
- Export and Download CSV From MySQL Database
- CRUD REST API
- CRUD REST API Example 2
- Enable HTTPS using Node
- How to send EMAIL using NodeJs?
- Dynamic dependent dropdown using NodeJs?
- Autocomplete Search
- Get and Send Data From Ajax Request
- Get and Post Data using Ajax
- Passport Authentication
- Node Js Data type
- Node Js Error
- Node Js Array Function
- Node Js String Function
- Puppeter Module
How to validate Form (Form Validation) in Node.Js?
Install Express Validator Module.
File Name :
c:\mynodeproject\nodeapp> npm install –save express-validator
######################### OR ##########################
npm install express-validator@5.3.0
// install specific version
npm uninstall express-validator
Create an HTML Form for Validation.
Create an HTML form with following input fields like :-
This HTML form will be used to validate the input data.
File Name : user-form.ejs
<!DOCTYPE html>
<html>
<head>
<head>
<body>
<form action="/validate-form" method="POST">
<label>First Name</label>
<input type="text" placeholder="Enter First Name" name="firstName" value="<%=(typeof inputData!='undefined')? inputData.firstName:''%>">
<p style="color: red;"><%=(typeof errors!='undefined' && typeof errors.firstName!='undefined' )? errors.firstName.msg:''%></p>
<label>Last Name</label>
<input type="text" placeholder="Enter Last Name" name="lastName" value="<%=(typeof inputData!='undefined')? inputData.lastName:''%>">
<p style="color: red;"><%=(typeof errors!='undefined' && typeof errors.lastName!='undefined' )? errors.lastName.msg:''%></p>
<label>Email Address</label>
<input type="email" placeholder="Enter Email Address" name="emailAddress" value="<%=(typeof inputData!='undefined')? inputData.emailAddress:''%>">
<p style="color: red;"><%=(typeof errors!='undefined' && typeof errors.emailAddress!='undefined' )? errors.emailAddress.msg:''%></p>
<label>Password</label>
<input type="password" placeholder="Enter Password" name="password">
<p style="color: red;"><%=(typeof errors!='undefined' && typeof errors.password!='undefined' )? errors.password.msg:''%></p>
<label>Confirm Password</label>
<input type="confirmPassword" placeholder="Enter Confirm Password" name="confirmPassword">
<p style="color: red;"><%=(typeof errors!='undefined' && typeof errors.confirmPassword!='undefined' )? errors.confirmPassword.msg:''%></p>
<button type="submit">Submit</button>
</form>
</body>
</html>
Write Rules for Form Validation
Include express validator module using require('express-validator')
Write all the validation rules within the exports.form=[]
File Name : validation-rule.js
const { check,sanitizeBody } = require('express-validator');
exports.form=[
// first Name validation
check('firstName').trim().notEmpty().withMessage('First Name required')
.matches(/^[a-zA-Z ]*$/).withMessage('Only Characters with white space are allowed'),
// last Name validation
check('lastName').notEmpty().withMessage('Last Name required')
.matches(/^[a-zA-Z ]*$/).withMessage('Only Characters with white space are allowed'),
// email address validation
check('emailAddress').notEmpty().withMessage('Email Address required').normalizeEmail().isEmail().withMessage('must be a valid email'),
// password validation
check('password').trim().notEmpty().withMessage('Password required')
.isLength({ min: 5 }).withMessage('password must be minimum 5 length')
.matches(/(?=.*?[A-Z])/).withMessage('At least one Uppercase')
.matches(/(?=.*?[a-z])/).withMessage('At least one Lowercase')
.matches(/(?=.*?[0-9])/).withMessage('At least one Number')
.matches(/(?=.*?[#?!@$%^&*-])/).withMessage('At least one special character')
.not().matches(/^$|\s+/).withMessage('White space not allowed'),
// confirm password validation
check('confirmPassword').custom((value, { req }) => {
if (value !== req.body.password) {
throw new Error('Password Confirmation does not match password');
}
return true;
})
]
Validate Input data on the form Submit
File Name : user-controller.js
const { validationResult, matchedData } = require('express-validator');
module.exports={
userForm:function(req, res) {
res.render('user-form');
},
validateForm:function(req,res){
const errors= validationResult(req);
if(!errors.isEmpty()){
var errMsg= errors.mapped();
var inputData = matchedData(req);
}else{
var inputData = matchedData(req);
// insert query will be written here
}
res.render('user-form', {errors:errMsg, inputData:inputData});
}
}
Create Routes to Validate Form
Create '/validate-form with the GET method to display the form
create /validate-form with POST method to validate the form on the form submit’
finally export the router.
File Name : user-route.js
const express = require('express');
const router = express.Router();
const userController=require('../controllers/user-controller');
const validationRule= require('../middlewares/validation-rule');
router.get('/validate-form', userController.userForm);
router.post('/validate-form',validationRule.form, userController.validateForm);
module.exports = router;
Include the Route in the app.js
File Name : app.js
var userRouter = require('./routes/user-route');
app.use('/', userRouter);
Run Node.js Application
File Name : app.js
npm start
Test on browser
http://localhost:3000/validate-form
Error :-
app.use(expressValidator());
^
TypeError: expressValidator is not a function
at Object. (/home/kirankamath/A/Project/node_react/basicNodeServer/app.js:26:9)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
solution :-
While using version 6, you will encounter the following error:
TypeError: expressValidator is not a function
To avoid this issue you can use the previous version which is 5.3.1
TypeError: expressValidator is not a function issue by reinstall the express validator NPM package and run the server again.
npm uninstall express-validator
npm install express-validator@5.3.0