Find the regex used by HTML5 forms for validation

前端 未结 3 1301
别跟我提以往
别跟我提以往 2021-02-07 02:57

Some HTML5 input elements accept the pattern attribute, which is a regex for form validation. Some other HTML5 input elements, such as, input type=email

相关标签:
3条回答
  • 2021-02-07 03:42

    The HTML5 spec currently lists a valid email address as one matching the ABNF:

    1*( atext / "." ) "@" ldh-str *( "." ldh-str )
    

    which is elucidated in this question. @SLaks answer provides a regex equivalent.

    That said, with a little digging through the source, shows that WebKit implemented email address validation using basically the same regex as SLaks answer, i.e.,

    [a-z0-9!#$%&'*+/=?^_`{|}~.-]+@[a-z0-9-]+(\.[a-z0-9-]+)*
    

    However, there is no requirement that email addresses be validated by a regex. For example, Mozilla (Gecko) implemented email validation using a pretty basic finite state machine. Hence, there needn't be a regex involved in email validation.

    0 讨论(0)
  • 2021-02-07 03:42

    this works for me: pattern="[^@]+@[^@]+.[a-zA-Z]{2,6}"

    0 讨论(0)
  • 2021-02-07 03:50

    The HTML5 spec now gives a (non-normative) regex which is supposed to exactly match all email addresses that it specifies as valid. There's a copy of it on my blog here: http://blog.gerv.net/2011/05/html5_email_address_regexp/ and in the spec itself: https://html.spec.whatwg.org/#e-mail-state-(type=email))

    The version above is incorrect only in that it does not limit domain components to max 255 characters and does not prevent them beginning or ending with a "-".

    Gerv

    0 讨论(0)
提交回复
热议问题