-2

I am new to nodejs and I am trying to validate my form using ejs template in express js. How can I validate the form entries and also display an error message in case the validation fails?

Here's my server code:

app.post('/formsubmit', function(req, res) 
    {
            console.log(req.body);
            var name =req.body.name;
            var email=req.body.email;
            var pwd =req.body.pwd;
            var age =req.body.age;

            var con = mysql.createConnection
                ({
                      host: "localhost",
                      user: "root",
                      password: "",
                      database: "demos"
                });

            con.connect(function(err) {
            if (err) throw err;
              console.log("Connected!");
              var sql = "INSERT INTO student (name, email,age) VALUES ('"+name+"','"+email+"','"+age+"')";
              con.query(sql, function (err, result) 
                {
                    if (err) throw err;
                     console.log("1 record inserted");
              });
            });             

        //console.log(record);
            res.send('Record Inserted Successfully');

}); 
Sivcan Singh
  • 1,775
  • 11
  • 15
  • Firstly, you need to sanitize the inputs (Don't allow any XSS attacks). Email - check with a regex, age - check if it's a number, pwd to be stored as string, name - check if there aren't any script tags etc - you can find all that after googling a bit or searching on stackoverflow. :) – Sivcan Singh Sep 15 '18 at 05:33
  • Your question is too broad. You need to add more details like validation of which fields and on the basis of what? requireness? length? – Ankit Agarwal Sep 15 '18 at 05:33
  • For instance - this is a good thread related to email validation using a regex: https://stackoverflow.com/questions/46155/how-to-validate-an-email-address-in-javascript – Sivcan Singh Sep 15 '18 at 05:35
  • @AnkitAgarwal : i just want if i submit blank form then error message should display , how can i pass error to view ( ejs ) and display errors ? – sheetal dhiman Sep 15 '18 at 05:36
  • @sheetaldhiman I would suggest you to look at this please https://www.npmjs.com/package/form-validate – Ankit Agarwal Sep 15 '18 at 05:37
  • @SivcanSingh : i want to display flash messages if user submit empty form thats it!. – sheetal dhiman Sep 15 '18 at 05:37
  • Look into express-validator and connect-flash npm modules – Edwin Babu Sep 15 '18 at 06:37

2 Answers2

1

You can validate form using express-validator and send flash messages using connect-flash.

const { check, validationResult } = require('express-validator/check');

app.post('/formsubmit', [check('title').not().isEmpty(),
                    check('content').not().isEmpty(),
                    check('title').not().isEmpty(),
                    check('content').not().isEmpty()]
                    ,function(req, res) {

            const errors = validationResult(req);
            if (!errors.isEmpty()) {
                req.flash('error', "Provide details for the blog");
                res.redirect('/notes');
            }
            else
            {
                //perform required operation
                res.send();
            }

}); 

Add these to your app.js

var flash = require('connect-flash');
app.use(flash()); // flash messages

app.use(function (req, res, next) {
    res.locals.success = req.flash('success');
    res.locals.info = req.flash('info');
    res.locals.error = req.flash('error');
    res.locals.user = req.user || null;
    next();
  });

Refer this link to learn about express-validator and flash messages

https://express-validator.github.io/docs/

sending flash message in express

Edwin Babu
  • 709
  • 8
  • 15
0

you have to handle this on the client side first so if the client clicked the submit button you have to check it everything is ok (all the required fields are fill with apparently correct values (date,email,phone number, ...)) then you send the data to the server.

EJS has nothing to do with form validation it is handled on the browser use jQuery or plain JS.

Of course on the server side you do check those values before accessing the database or any other action