Reputation: 1606
I am trying to validate a string only if its first 5 characters are numeric and last 5 characters are letters:
What I have tried:
var userId = "12345abcde";
// Get First and Second Five Characters
var firstFive = userId.substring(0, 5);
var secondFive = userId.substring(5, 10);
// get Global Letter and Nummers
var aStr = /[a-z, A-Z]/g;
var aNum = /[0-9]/g;
var c = userId.match(aNum);
// Try firstFive first...
if (firstFive === c) {
alert('yes');
} else {
alert('nop');
}
This alerts nop
.
Is this because firstFive
is string and c
is object? Where is the error in my thinking?
Live example: http://jsfiddle.net/xe71dd59/1/
Any tips? Thanks in advance!
Upvotes: 0
Views: 1032
Reputation: 21
Try to do this way:
var userId = "12345abcde";
var result = /^[0-9]{5}.*[a-z]{5}$/i.test(userId);
if (result) {
alert('yes');
}else{
alert('nop');
}
Upvotes: 0
Reputation: 2528
match
returns an array of results or NULL if none were found.
var c = firstFive.match(aNum);
if(c!=null)
{
if(c.length==5)
{
alert("Yes");
}
}
Upvotes: 1