HTML5 minimum character length validation ignoring spaces and tabs

前端 未结 2 1337
温柔的废话
温柔的废话 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:29

    I managed a silly hack that does what you asked:

    
    

    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?

提交回复
热议问题