Form validation in NodeJS

Our Goals –
• Create a HTML Form and before submit validate the data with EJS Template

Assumption
We already have a NodeJs project “myschool” in our working directory. If you don’t have the project then please create it. We have discussed it on our previous tutorial.

To do so –
1. Install express-validator by typing “npm install express-validator –save”
2. Open “home.ejs” from “app_views” folder and edit the file as –

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<% include header %>
<body>
    <h1><%= topicHead %></h1>
    <form name="form1" method="POST" action="/student/add">
    <table>
        <tr>
        <td>First name</td>
        <td><input type="text" name="fname" ></td>
        </tr>
        <tr>
        <td>last name</td>
        <td><input type="text" name="lname" ></td>
        </tr>
        <tr>
        <td colspan="2"><input type="submit" value="Save" ></td>
        </tr>
    </table>
    </form>
    <% if(errors){ %>
        <ul>
        <% errors.forEach(function( err){ %>
            <li> <%= err.msg %> </li>
        <% }) %>
        </ul>
    <%}else{%>
        <div> Data Entered as <%= userValue.first %>  <%= userValue.last %> </div>
    <%}%>
</body>
<% include footer %>

<% include footer %>
3. Edit “app.js” as –

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
var express = require('express');
var parser = require('body-parser');
var path = require('path');
var expressValidator = require('express-validator');
var app = express();
app.set('port',(process.env.PORT || 5000));
app.use(parser.urlencoded({ extended: false }))
app.use(parser.json())
 
app.use(function(req,res,next){
    res.locals.userValue = null;
    res.locals.errors = null;
    next();
})
 
app.set('view engine','ejs');
app.set('views',path.join(__dirname,'app_views'))
 
app.use(expressValidator({
  errorFormatter: function(param, msg, value) {
      var namespace = param.split('.')
      , root    = namespace.shift()
      , formParam = root;
 
    while(namespace.length) {
      formParam += '[' + namespace.shift() + ']';
    }
    return {
      param : formParam,
      msg   : msg,
      value : value
    };
  }
}));
// End of express-validator
 
app.get('/',function(req,res){
    res.render('home',{
        topicHead : 'Student Form'
    });
    console.log('user accessing Home page');
});
app.post('/student/add',function(req,res){
     
    // Check Input Field
    req.check('fname', 'First Name is required').notEmpty();
    req.check('lname', 'Last Name is required').notEmpty();
     
    var errors = req.validationErrors();
    if(errors){
        res.render('home',{
            topicHead : 'Student Form',
            errors : errors
        });
        console.log('Error');
    }else{
        var student = {
            first : req.body.fname,
            last : req.body.lname
        }
        console.log(student);
        res.render('home',{
            userValue : student,
            topicHead : 'Student Form'
        });
        console.log('OK');
    }  
});
app.listen(app.get('port'),function(){
    console.log('server running on port '+app.get('port'));
})

4. Considering we have installed “nodemon” in our nodejs and run “nodemon”

5. Now browser will show our first EJS template based web Form @ http://localhost:5000/

6. Without entering any value hit the submit button and you will get the following screen-

7. Now provide First name as “tanmay and Last name as “sarkar” and click Save button , it will looks like –

Thank you.

Related posts:

One thought on “Form validation in NodeJS”

Leave a Reply

Your email address will not be published. Required fields are marked *