Full Post Page
 

NodeJS ExpressJs form Validation

Category: NODE JS & Written by Admin On May-26-2025 16:50:59

NODEJS EXPRESSJS FORM VALIDATION EXPRESSJS :implement form VALIDATION STEP 1 npm install express-validator STEP 2 const{body,validatorResult}=require("express-validator"); step 3 var validatorRegistration=[ body('username').notEmpty().withMessage('Username is require'), body('password').isLength({min:5,max:10}). withMessage("password must be between 5 to 5 and 20 characters long") ] step 4 (middlerware) app.post('/saveForm',validatorRegistration,(req,res)=>{ const result= validatorResult(req); res.send(result) }); EXPRESSJS :form validator method MORE notEmpty() isEmail() isLength(options) isNumberic() ,isAlpha() isAlphanumeric() isURL() isIn() (show array value message) isStrongPassword() isUpperCase(),isLowercase() matches(pattern)() =>(check self VALIDATION for regular express) SanitiZation VALIDATION method trim() Itrim() rtrim() escape() unescape() normalizeEmail() ==>extra . remove toInt() toFloat() toBoolean() Custom validator Custom(validator) .CustomSanitizer(sanitizer) THREE METHOD USE TOGETHER body("first_name") .notEmpty().withMessage("First name is require") .trim() .isLength({min:5}).withMessage("first_name mst have 5 characters") .escape() .isAlpha().withMessage("First name has isAlpha characters") <,>,&,',",`,\and/ Html encoded entities Starign lab:::: website for package npmjs.com =>here search express validator copy command https://www.npmjs.com/package/express-validator npm i bootstrap npm install ejs npm install express-validator npm i express-validator check In node_module folder (validator) app.js file // 1. inclue express const express=require('express'); const app=express(); // object app const {body,validationResult}=require("express-validator") app.set('view engine','ejs') app.use(express.json()) app.use(express.urlencoded({ extended:false})) var validationRegistration=[ body('username') .notEmpty().withMessage("username is require.") .isLength({min:3}).withMessage("Username must be at least 5 charactor") .trim() .isAlpha().withMessage("Username must only letter only") // custom self validaor .custom(value=>{ if(value==='admin'){ throw new Error('User name "admin" is not allowed.') } }), body('usermail') .isEmail().withMessage("Pleaser provide a Email Id") .normalizeEmail(), body('userpass') .isLength({min:5,max:20}).withMessage("mail must be between 5 to 20 charactor long") .isStrongPassword().withMessage("password must be strong"), body('userage') .isNumeric().withMessage("please provide a vaild Email Id.") .isInt({min:18}).withMessage("Age must be least 18 years old"), body('usercity') .isIn(['Delhi','Mumbai',"Agra",'Goa']).withMessage("city must be Delhi,Goa,Agra,or mumbai") ] //3. Route app.get('/myform',(req,res)=>{ // res.render("myform") // show ejs from res.render('myform',{errors:0}) // starting 0 value }); app.post('/saveform',validationRegistration,(req,res)=>{ const error= validationResult(req) if(error.isEmpty()){ res.send(req.body) } //res.send(error) // error show in json format res.render('myform',{errors:error.array()}) // error show in html files //errors key :error object }) // B.NB IF VISITOR OPEN UNKNOWN ROUTE THEN CREATE FOR THIS Middleware app.use((req,res)=>{ res.send("<h2> Error 404 pange not found </h2>") }) // 2. server app.listen(3000, () => { console.log('My App is running on port 3000!'); }); myform.ejs <% if(errors.length > 0) { %> <div class="row mb-3"> <div class="col-6"> <ul class="alert alert-danger"> <% errors.forEach(error => { %> <li><%= error.msg %></li> <% }); %> </ul> </div> </div> <% } %>

Comments

Share your thoughts about this post

Why Choose Us:

Experienced Instructors: Our team of experienced instructors are passionate about coding and dedicated to helping you succeed. With years of industry experience and a knack for teaching, they'll guide you every step of the way. Beginner-Friendly Content: Don't worry if you're new to coding. Our tutorials are designed with beginners in mind, starting from the fundamentals and gradually building up to more advanced topics. Updated Content: Coding is a rapidly evolving field, and we're committed to keeping our content up-to-date with the latest trends, technologies, and best practices. Community Support: Learning to code is more fun and effective when you're part of a supportive community. Join our online community forums to connect with fellow learners, share insights, and collaborate on projects. Get Started Today:



Recent Posts

Advance Js Fetch API Part-5

June-06-2025 21:23:08


Advance Js Promise Part-4

June-06-2025 11:35:05


Advance js oop part-3

June-06-2025 08:25:42


ExpressJs API With Image Crud-3

June-02-2025 21:09:41


NodeJs API-MVC-2

June-02-2025 10:56:22


ExpressJs API Crud-1

June-02-2025 10:27:58


ExpressJs Files upload

June-02-2025 10:15:40


NodeJS Cookie and CsrfToken

May-30-2025 19:20:40


ExpressJS Session

May-30-2025 19:14:29


ExpressJS NodeJs Crud Part-2

May-27-2025 21:52:18


ExpressJS NodeJS Crud Part-1

May-27-2025 21:33:30


ExpressJS Authentication

May-26-2025 17:11:41


NodeJS ExpressJS Files Upload

May-26-2025 16:53:29



Angular Introduction

May-13-2025 21:02:32



Advance Js part-1

May-12-2025 15:41:29