【问题标题】:Password confirmation(form validation) from server-side to client side从服务器端到客户端的密码确认(表单验证)
【发布时间】:2015-05-04 09:40:46
【问题描述】:

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

需要创建输入验证(实际上是“密码确认”和“电子邮件”)还需要使用“正则表达式”。我如何实现这种方法?我在客户端创建了输入数据验证。它的工作原理。也许我只需要把这段代码放在服务器上?在 google 中搜索并没有给我预期的结果...我看到了许多验证方法 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!');

  });
});

【问题讨论】:

  • 显示您的客户端验证码。
  • 您的问题并不清楚,甚至您没有提供您使用的服务器端语言等详细信息。
  • 你说得对。我没有使用“ req.checkBody('email').isEmail(); ”但是当我不在客户端使用javascript代码时它是有效的!现在我明白为什么了:)谢谢你!
  • 哦...它正在工作。但是我在密码确认方面遇到了麻烦...需要了解如何解决此问题...
  • 感谢您的帮助!

标签: javascript regex node.js validation express


【解决方案1】:

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

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

对于密码和确认密码的验证,您应该使用-

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

【讨论】:

    猜你喜欢
    • 2011-10-17
    • 2013-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 2011-06-21
    相关资源
    最近更新 更多