MeteorJS电子邮件表单验证

blu*_*inc 2 javascript forms validation meteor

这里总新手.我正在尝试为订阅新闻稿表单进行客户端表单验证.我的客户端代码是这样的.

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);
     }
Run Code Online (Sandbox Code Playgroud)

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

Dav*_*don 7

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

正则表达式

正则表达式可用于快速和脏的电子邮件验证.他们会抓住任何明显虚假的电子邮件,x@y.z或者foo@bar,但这是关于他们准确性的限制.当现有用户没有动机输入无效地址时,我们会在客户端的应用内使用这些内容.这是一个例子:

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

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

您可以在此处详细了解电子邮件正则表达式.

Mailgun

如果您认为用户可以故意输入无效地址,您可以带出bug枪并调用mailgun电子邮件验证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;
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

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

有关更多详细信息,请参阅文档.