2013-03-11 55 views
0

我試圖檢查字符串是否都是a-zA-Z0-9但這不起作用。任何想法爲什麼?用於檢查字符串是否爲a-zA-Z0-9的正則表達式

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"); 
} 
+2

您的STRING一個白色的空間,所以它不符合你的模式。 – 2013-03-11 19:32:39

+0

這是故意的 – timpone 2013-03-11 19:34:33

+0

var pattern =/^ [a-zA-Z0-9 \ s] * $ /; – Girish 2013-03-11 19:36:38

回答

5

exec()返回null如果沒有發現匹配,這是typeof對象不undefined

你應該使用這樣的:

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'); 

或者只是使用了test method

var matchStatus = pattern.test(myString); // a boolean 
+0

THX BERGI,這是我與 – timpone 2013-03-11 19:43:28

1

,如果im沒有錯,你的正則表達式沒有規定空間和您的字符串有空間在裏面。如果你想允許的空間嘗試這種方式/^[A-ZA-Z0-9 \] * $/

+0

沒有必要去在一組逃逸的空間。 – VisioN 2013-03-11 19:33:58

+1

正確..或者更好/^[a-zA-z0-9 \ s] * $/ – 2013-03-11 19:34:06

+0

@ZiaudDeen:OPs問題不是正則表達式不匹配(這是意圖),但是'matchStatus'沒有設置爲0. – Bergi 2013-03-11 19:46:35

1

嘗試,如果沒有比賽,沒有不確定

if(matches === null){ 
    alert('within here'); 
    matchStatus=0; // matchStatus is false 
}; 

if(matchStatus===1){ 
    alert("there was a match"); 
} 

Regex.exec返回null。所以你需要測試一下。

似乎像您期望的那樣工作:fiddle

的文檔execMDN

+0

thx,good sol'n too – timpone 2013-03-11 19:43:11

0

我只測試它 - 在這種情況下:

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"); 
} 
+0

不,我試圖測試一些不被接受的東西 – timpone 2013-03-11 19:35:42

0
function KeyString(elm) 
{ 
    var pattern = /^[a-zA-Z0-9]*$/; 

    if(!elm.value.match(pattern)) 
    { 
     alert("require a-z and 0-9"); 
     elm.value=''; 
    } 
} 
相關問題