Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 minimum character length validation ignoring spaces and tabs

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 because user will just put spaces then. I need regex such that it will accepts space and tabs but able to count only character's. Example "ronny jones" this should give 10.

In javascript we do it using something like this, I am looking for similar thing in HTML5

      var name = document.forms['contact']['name'].value.replace(/ /g,""); // remove whitespace
  if(name.length<6){  // count number of character.
     document.getElementById('message').innerHTML="Enter correct Name";   
     return false;
  }

I found one related question to this on SO : Is there a minlength validation attribute in HTML5? but it accepts spaces and tabs, which I don't want.

Below is my code with HTML5 pattern,

    <input type="text" name="name" class="form-control" placeholder="Your Full Name" pattern="[A-Za-z]{6,}" title="Name should have atleast 6 characters." required="" />
like image 930
WeAreRight Avatar asked Jan 19 '17 05:01

WeAreRight


1 Answers

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?

like image 132
Robbie Avatar answered Oct 13 '22 12:10

Robbie