user2441391
user2441391

Reputation: 339

Regular expression that checks if input is at the maximum 25 characters long and has a space?

I need a regular expression that checks if the input is at the most 25 characters long and has two strings (first and last name) separated by a space character. So far I have this,

var name=$('#name').val();
var namePattern = /^[\sA-Za-z]{25}$/;

if(namePattern.test(name))
{
return true;
}

Upvotes: 1

Views: 289

Answers (2)

Ro Yo Mi
Ro Yo Mi

Reputation: 15000

Description

This expression will:

  • validate the string is at most 25 characters long
  • skip over any leading or trailing whitespace
  • required 1 white space character in the middle
  • capture the first and last name into two separate capture groups
  • allow hyphenated and ' in the names. Of course what you consider a valid name is really upto you. Be careful as [a-z] will not validate accented characters

.

^(?=\s*\S[^\r\n]{0,23}\S\s*\Z)\s*([a-z-']+)\s([a-z-']+)\s*\Z

enter image description here

Example

Live Demo: http://www.rubular.com/r/j9jfyJrIqP

Sample Text

Note in the live example and this sample text, there are leading and trailing spaces.

      Mc'David Johnson-Smith     

Capture Groups

[0][0] =       Mc'David Johnson-Smith     
[0][2] = Mc'David
[0][3] = Johnson-Smith

Upvotes: 0

David Thomas
David Thomas

Reputation: 253318

Why use regular expressions?

if (name.length < 26 && name.indexOf(' ') > 1) {
    // the name's 25 characters or less
    // there's at least one character before the space
}

This is, obviously, a JavaScript implementation, but this is because you have both and attached to your question.

For the problem of 'Bruce ' passing validation, using the $.trim() function on the string you assign to the name variable, and split() on that variable, will prevent that false-positive. Given the following HTML:

<ul>
    <li>Bruce</li>
    <li>Bruce </li>
    <li>Bruce Wayne</li>
    <li>Brucewayne</li>
</ul>

With the following, since you tagged the question with jQuery:

$('li').addClass(function(){
    var name = $.trim($(this).text());
    return name.length < 26 && name.split(/\s+/).length > 1 ? 'pass' : 'fail';
});

JS Fiddle demo.

Upvotes: 5

Related Questions