Reputation: 339
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
Reputation: 15000
This expression will:
'
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
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
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 php and javascript 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';
});
Upvotes: 5