【问题标题】:MeteorJS email form validationMeteorJS 电子邮件表单验证
【发布时间】:2014-12-28 21:01:13
【问题描述】:

这里是新手。 我正在尝试为订阅时事通讯表单进行客户端表单验证。我的客户端代码就是这样。

Template.body.events({
    "submit .new-subscriber": function (event) {
      // This function is called when the new task form is submitted
      var newEmail = event.target.newEmail.value;
     if (newEmail is email?){

     Meteor.call("addNewSubscriber", newEmail);
     }

我不确定如何在这里执行表单验证?我可以执行相同的服务器端吗?

【问题讨论】:

  • 检查本教程是否适合您,Gentlenod Email with meteor Accounts
  • @Etjana 我可以按照教程进行操作,谢谢。但它仍然无法帮助我验证用户是否确实输入了有效的电子邮件,例如name@email.com

标签: javascript forms validation meteor


【解决方案1】:

我们目前在 Edthena 使用两种不同的方法进行电子邮件验证,具体取决于具体情况。希望其中一项或两项都能满足您的需求。

正则表达式

正则表达式可用于快速而肮脏的电子邮件验证。他们将捕获任何明显伪造的电子邮件,例如x@y.zfoo@bar,但这大约是他们准确性的极限。当现有用户没有动机输入无效地址时,我们会在客户端的应用程序中使用这些。这是一个例子:

var isEmailValid = function(address) {
  return /^[A-Z0-9'.1234z_%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(address);
};

在您的情况下,您可以在提交处理程序中添加对isEmailValid 的调用。如果函数返回false,您可以显示错误而不是调用addNewSubscriber

您可以阅读有关电子邮件正则表达式here的更多信息。

邮筒

如果您认为用户可能故意输入无效地址,您可以拿出大炮并致电mailgun email validation API。这牺牲了速度(结果可能需要几秒钟才能返回)以显着提高准确性(mailgun 会检查目标域上是否存在 MX 记录)。我们在面向公众的表单中使用这种方法。

Meteor.methods({
  isEmailValid: function(address) {
    check(address, String);

    // modify this with your key
    var result = HTTP.get('https://api.mailgun.net/v2/address/validate', {
      auth: 'api:pubkey-XXXXXXXXXXXXX',
      params: {address: address.trim()}
    });

    if (result.statusCode === 200) {
      // is_valid is the boolean we are looking for
      return result.data.is_valid;
    } else {
      // the api request failed (maybe the service is down)
      // consider giving the user the benefit of the doubt and return true
      return true;
    }
  }
});

在本例中,isEmailValid 被实现为一个方法,可以根据您的需要在服务器或客户端上调用。请注意,您需要获取 API 密钥并将 http 包添加到您的应用中,并使用 meteor add http

更多详情,请参阅docs

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-27
    • 2013-09-08
    • 1970-01-01
    • 2014-05-28
    • 2018-08-17
    • 2019-03-27
    • 1970-01-01
    相关资源
    最近更新 更多