Serge Enin
Serge Enin

Reputation: 51

Password confirmation(form validation) from server-side to client side

I have Express.js server. Running in node.js. Using javascript server side language. There I have signup sipmle form, register new user and save users in mongoDb. POST method.

<form action="/new" method="POST">Name:
  <input type="text" name="name" class="name"/><br/>Phone number:
  <input type="text" name="phone" class="phone"/><br/>email:
  <input type="email" name="email" class="email"/><br/>Password:
  <input type="password" id="p1" name="pass" class="pass"/><br/>Confirm password:
  <input type="password" id="p2" name="confirm" class="confirm"/><br/>
  <input type="submit" value="Submit" onclick="return validateForm()"/>
</form>

Need to create input validation(actualy it's "Password confirm" and "Email")Also need to use "regex". How I can realize this method?I created input data validation on client-side.It's works.Maybe I just need put this code in the server? Searching in google don't give me expected results... I saw many validation methods validator.js but not finde detailed code...Thank you for helping:)

<script>
function validateForm (event) {
var p1 = document.getElementById('p1');
var p2 = document.getElementById('p2');
if (p1.value !== p2.value) {
alert('Password check!');
return false;
}
// check email
var email = document.getElementById('email');
// regex
var email_regexp = /[0-9a-zа-я_A-ZА-Я]+@[0-9a-zа-я_A-ZА-Я^.]+\.[a-zа-яА-ЯA-Z]{2,4}/i;
if (!email_regexp.test(email.value)) {
alert('Check email');
return false;
}
}
</script>

also here is my registration server side code:

 app.use(bodyParser());

mongoose.connect('mongodb://localhost/test');

var Schema = new mongoose.Schema({
  name    : String,
  phone: String,
  email : String,
  pass : String,
  confirm : String
});

var user = mongoose.model('emp', Schema);

app.post('/new', function(req, res){

  new user({
    name : req.body.name,
    phone: req.body.phone,
    email: req.body.email,
    pass: req.body.pass,
    confirm: req.body.confirm   
  }).save(function(err, doc){
    console.log(user); 
    if(err) res.json(err);
    else    res.send('Successfully inserted!');

  });
});

Upvotes: 2

Views: 2655

Answers (1)

Manik Arora
Manik Arora

Reputation: 4792

For validating email you should use-

req.checkBody('email').isEmail();

For the validation of Password and Confirm Password you should use-

req.assert('confirm', 'Password and Confirm Password should be same.').equals(req.body.pass);
var mappedErrors = req.validationErrors(true);

Upvotes: 4

Related Questions