2012-06-12 127 views
3

我正在使用以下正則表達式來檢查名稱格式。正則表達式來檢查''

/^([A-Za-z0-9\[email protected]])*$/ 

名稱應只包含字母數字字符,_@.-和空間。但是這個正則表達式並不限制'\'。

+1

你如何測試它?瑣事:'「ab \ c」===「abc」' - '無效'斜線被忽略。 – Kobi

+2

請提供一個錯誤場景的生活場景,我不能在jsfiddle中重現它,除非使用@Kobi提到的不必要的轉義。 –

+0

像這樣的事情Jaison \ 123等沒有正確檢查。我正在使用測試方法 – Jaison

回答

0

你的代碼工作:

Test 1: 
"\\".search(/^([A-Za-z0-9\[email protected]])*$/); 

//-1 

Test 2: 
"Apple\\Microsoft".search(/^([A-Za-z0-9\[email protected]])*$/); 

//-1 
+0

解釋爲什麼你要逃避字符串中的轉義字符,我會+1。 –

+2

@FabrícioMatté - 你是什麼意思?如果您希望字符串包含反斜槓,則必須轉義它們。寫'\微軟'可能是一個錯誤,我*嘗試*評論。 – Kobi

+0

我的意思是?看看這個問題的評論。 「你的代碼正在工作」不是IMO的答案,如果你不解釋OP在哪裏做錯了。 –

0

你可以試試這個一個

if (/^([\w\[email protected]]+)$/i.test(subject)) { 
    // Successful match 
} else { 
    // Match attempt failed 
} 
0

我修改你的表達/^([A-Za-z0-9 [email protected]])*$/; insted的的\ S空間給

試試這個

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<script type="text/javascript" language="javascript"> 

function chkit() 
{ 
    var password=document.getElementById('password').value; 
    var namep=/^([A-Za-z0-9 [email protected]])*$/; 

    var name=document.getElementById('name').value; 
    if(name!="") 
    { 
     if(!namep.test(name)) 
      { 
       alert('name not in format'); 
      } 
      else 
      { 
       alert('name In format'); 
      } 
    } 
} 

</script> 
</head> 

<body> 
    <p> 
    <label for="name">name</label> 
    <input name="name" type="text" id="name" onblur="chkit();" /> 
    </p> 
</body> 
</html> 
2

試試這個

[A-Za-z _- @。 0-9] {1,250}