I am trying to check if a string is all a-zA-Z0-9
but this is not working. Any idea why?
var pattern=/^[a-zA-Z0-9]*$/;
var myString='125 jXw'; // this shouldn't be accepted
var matches=pattern.exec(myString);
var matchStatus=1; // say matchStatus is true
if(typeof matches === 'undefined'){
alert('within here');
matchStatus=0; // matchStatus is false
};
if(matchStatus===1){
alert("there was a match");
}
I am trying to check if a string is all a-zA-Z0-9
but this is not working. Any idea why?
var pattern=/^[a-zA-Z0-9]*$/;
var myString='125 jXw'; // this shouldn't be accepted
var matches=pattern.exec(myString);
var matchStatus=1; // say matchStatus is true
if(typeof matches === 'undefined'){
alert('within here');
matchStatus=0; // matchStatus is false
};
if(matchStatus===1){
alert("there was a match");
}
Share
Improve this question
edited Apr 20, 2015 at 8:05
mins
7,51413 gold badges69 silver badges86 bronze badges
asked Mar 11, 2013 at 19:29
timponetimpone
20k36 gold badges128 silver badges223 bronze badges
3
- 2 Your string has a white space so it doesn't match your pattern. – CD.. Commented Mar 11, 2013 at 19:32
- var pattern=/^[a-zA-Z0-9\s]*$/; – Girish Commented Mar 11, 2013 at 19:36
- tab value is not filter, I copy from text editor with tab, eg. 'test% $test', space is with 2 tab, but its not filter at all, result as 'test test' – Apache Commented Feb 12, 2014 at 3:31
5 Answers
Reset to default 7exec()
returns null
if no match is found, which is typeof
object not undefined
.
You should use this:
var matches = pattern.exec(myString); // either an array or null
var matchStatus = Boolean(matches);
if (matchStatus)
alert("there was a match");
else
alert('within here');
Or just use the test
method:
var matchStatus = pattern.test(myString); // a boolean
If im not wrong, your regex has no provision for SPACE and your string has space in it. If you want to allow space try this way /^[a-zA-z0-9\ ]*$/
Try
if(matches === null){
alert('within here');
matchStatus=0; // matchStatus is false
};
if(matchStatus===1){
alert("there was a match");
}
Regex.exec returns null if there's no match, not undefined. So you need to test that.
It seems to work as you expect like that: fiddle
Documentation for exec
: MDN
function KeyString(elm)
{
var pattern = /^[a-zA-Z0-9]*$/;
if( !elm.value.match(pattern))
{
alert("require a-z and 0-9");
elm.value='';
}
}
I would test it only - in this case:
var pattern = /^[a-z0-9]+$/i;
var myString = '125 jXw';
var matchStatus = 1; // say matchStatus is true
if (!pattern.test(matches)) {
matchStatus = 0; // matchStatus is false
};
if(matchStatus === 1){
alert("there was a match");
}