从服务器端到客户端

时间:2015-05-04 09:40:46

标签: javascript regex node.js validation express

我有Express.js服务器。在node.js中运行使用javascript服务器端语言。我有注册sipmle表单,注册新用户并在mongoDb中保存用户。 POST方法。

<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>

需要创建输入验证(实际上是&#34;密码确认&#34;和&#34;电子邮件&#34;)还需要使用&#34; regex&#34;。我如何才能实现这种方法?我在客户端创建了输入数据验证。它的工作原理。也许我只需要将这些代码放在服务器中?在谷歌搜索不会给我预期的结果......我看到许多验证方法validator.js但没有找到详细的代码...谢谢你的帮助:)

<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>

这里也是我的注册服务器端代码:

 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!');

  });
});

1 个答案:

答案 0 :(得分:4)

要验证电子邮件,您应该使用 -

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

要验证密码和确认密码,您应该使用 -

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