繁体   English   中英

从服务器端到客户端的密码确认(表单验证)

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

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

需要创建输入验证(实际上是“密码确认”和“电子邮件”),还需要使用“ regex”。 我如何实现这种方法?我在客户端创建了输入数据验证。它的工作原理。也许我只需要将此代码放在服务器中即可? 在google中搜索不会给我期望的结果...我看到了许多验证方法validateator.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!');

  });
});

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM