HTML5 minimum character length validation ignoring spaces and tabs

前端 未结 2 1338
温柔的废话
温柔的废话 2021-01-18 10:17

I am using HTML5 \'pattern\' attribute with \'required\' for validation of input boxes. HTML5\'s required attribute works but it can accept spaces and tabs which is not good

相关标签:
2条回答
  • 2021-01-18 10:28
     <form action="demo.php">
        <input id="name" type="text" pattern="^((?:\s*[A-Za-z]\s*){6,})$">
        <input type="submit">
     </form>
    

    this will work for your case .. its exacly how you want it. i have set limit of character is from 6 to 40..

    0 讨论(0)
  • 2021-01-18 10:29

    I managed a silly hack that does what you asked:

    <input type="text" name="name" class="form-control" placeholder="Your Full Name" pattern="\s*(\S\s*){6,}" title="Name should have at least 6 characters." required="" />
    

    There must be 6 non-space characters for this to pass. so "asdfgh", " abc def " will work, but "abc de" fails.

    It DOES NOT work for your comment about "there's a space after Anthony" but as Anthony contains 6 characters, then it's fine? If not, can you clarify further in the question.


    To explain how it works:

    • it takes a pattern of "take 1 non-space character" \S followed by "none-or-more space characters" \s*
    • you need the pattern to be matched 6 or more times (pattern){6,} i.e. (\S\s*){6,}
    • then allow non-or-more spaces at the front \s*

    If you want to limit the characters allowed to Alpha only, change the \S to [A-Za-z].

    Yes, it's a hack IMO as it will be hell to parse internally on long strings. But does the job. You might want to mix with maxlength to limit that as well?

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