加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails正则表达式电子邮件验证,不允许空格

发布时间:2020-12-17 02:25:38 所属栏目:百科 来源:网络整理
导读:我目前正在使用此代码进行电子邮件验证: /A[w+-.]+@[a-zd-.]+.[a-z]+z/i 问题是它仍然接受带有ab c@gmail.com等空格的电子邮件. 我已经尝试了很多不允许使用空格的代码变体,但是它没有刷新页面顶部的错误消息,而是给了我这个错误: The provided reg
我目前正在使用此代码进行电子邮件验证:

/A[w+-.]+@[a-zd-.]+.[a-z]+z/i

问题是它仍然接受带有ab c@gmail.com等空格的电子邮件.

我已经尝试了很多不允许使用空格的代码变体,但是它没有刷新页面顶部的错误消息,而是给了我这个错误:

The provided regular expression is using multiline anchors (^ or $),
which may present a security risk. Did you mean to use A and z,or
forgot to add the :multiline => true option?

解决方法

您缺少开始和结束锚标记,因此您可以参考此链接 Regular expressions with validations in RoR 4并且正确的正则表达式将是,

/^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}$/i

您应该尝试使用此正则表达式进行电子邮件验证,此正则表达式将满足您的所有要求并检查所有必需的可能验证.

^[_A-Za-z0-9-+]+(.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(.[A-Za-z0-9]+)*(.[A-Za-z]{2,})$

以下是对正则表达式的解释,它对于理解验证很有用

^           #start of the line
  [_A-Za-z0-9-+]+ #  must start with string in the bracket [ ],must contains one or more (+)
  (         #   start of group #1
    .[_A-Za-z0-9-]+   #     follow by a dot "." and string in the bracket [ ],must contains one or more (+)
  )*            #   end of group #1,this group is optional (*)
    @           #     must contains a "@" symbol
     [A-Za-z0-9-]+      #       follow by string in the bracket [ ],must contains one or more (+)
      (         #         start of group #2 - first level TLD checking
       .[A-Za-z0-9]+  #           follow by a dot "." and string in the bracket [ ],must contains one or more (+)
      )*        #         end of group #2,this group is optional (*)
      (         #         start of group #3 - second level TLD checking
       .[A-Za-z]{2,}  #           follow by a dot "." and string in the bracket [ ],with minimum length of 2
      )         #         end of group #3
$          #end of the line

测试输出:

Email is valid : abc@yahoo.com,true
Email is valid : abc-100@yahoo.com,true
Email is valid : abc.100@yahoo.com,true
Email is valid : abc111@abc.com,true
Email is valid : abc-100@abc.net,true
Email is valid : abc.100@abc.com.au,true
Email is valid : abc@1.com,true
Email is valid : abc@gmail.com.com,true
Email is valid : abc+100@gmail.com,true
Email is valid : abc-100@yahoo-test.com,true
Email is valid : abc,false
Email is valid : abc@.com.my,false
Email is valid : abc123@gmail.a,false
Email is valid : abc123@.com,false
Email is valid : abc123@.com.com,false
Email is valid : .abc@abc.com,false
Email is valid : abc()*@gmail.com,false
Email is valid : abc@%*.com,false
Email is valid : abc..2002@gmail.com,false
Email is valid : abc.@gmail.com,false
Email is valid : abc@abc@gmail.com,false
Email is valid : ab c@gmail.com,false
Email is valid : abc@gmail.com.1a,false

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读