Validate Multiple Email Addresses with HTML5

前端 未结 3 1180
你的背包
你的背包 2021-02-15 14:06

I\'m trying to construct an email form that takes multiple comma separated emails as an input and verifies them using HTML5. I want to use the following regex to sanity check t

相关标签:
3条回答
  • 2021-02-15 14:16

    Is there a way to mix pattern and multiple so the regex checks each item in the comma separated list?

    Yes. If the regex to match an element is foo, then

    ^(?:foo(?:,(?!$)|$))*$
    

    will match a comma separated list of foos.

    The separator is (?:,(?!$)|$) which will match either a required comma that does not end the input, or the end of input.

    That separator is horribly ugly, but allows you to avoid duplicating the "foo" as long as no suffix of the separator is a required non-empty prefix of the body.

    0 讨论(0)
  • 2021-02-15 14:18

    You could read the input in with javascript and split the input on commas.

    function() {
    var inputString = document.getElementById('emailinput').value;
    var splitInput = inputString.split(',');
    
    var pattern = /"your regex pattern"/;
    
    var match = true;
    
    for(i=0;i<splitInput.length;i++) {
      if(!splitInput.match(pattern)){
        match = false;
      }
    }
    
    return match;
    }
    
    0 讨论(0)
  • 2021-02-15 14:26

    Try this:

    <input type="email" multiple pattern="^([\w+-.%]+@[\w-.]+\.[A-Za-z]{2,4},*[\W]*)+$" value="">
    

    Update:

    Using <input type="email" value="" multiple> does seem to be bugged by letting "a@b" pass. Though I would go with this method to keep the semantics as you said, and simply use validation on the server side as well just in case someone tries to submit an email like "a@b".

    Just as a note, you should always validate on the server side for security reasons anyway, as client side validation can be bypassed very easily.

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