2013-04-23 77 views
-2

我要檢查,如果一個變量的值是不是所有的文字,例如,如果變量不等於文本,然後顯示錯誤信息的驗證:名和姓

if (($(regname).match(/[^a-z ]/gi))) { 
       $('p.validfirstname').fadeIn(300); 
} 

我不是確定如何做到這一點,所以上面的代碼可能是錯誤的。

+1

什麼是'regname'? – tymeJV 2013-04-23 16:10:22

+0

一個變量,例如var regname =「Henry1」 – user1937021 2013-04-23 16:13:31

+0

if regname =「Henry1」' - $(regname)'應該做什麼?我想你只是想regname.match – 2013-04-23 16:17:11

回答

2

這將是這樣的:

var matches = $(regname).val().match(/[^a-zA-Z]/g); 


if(matches && matches.length > 0) { 
// valid first name 
} 

這是怎麼回事假設寄存器名是輸入域CSS選擇器。如果它不是輸入元素,請使用.text()而不是.val()。如果它不是一個HTML元素,您可以直接撥打.match()直接撥打regname

如果您將首字母和姓氏都存儲爲單個字符串,那麼在檢查非字母字符之前,最好使用split()

function checkNames() 
{ 
    var firstAndLast = $(regname).val().split(' '); 
    var first = firstAndLast[0]; 
    var last = firstAndLast[1]; 

    if(checkName(first)) 
    { 
    // valid first name 
    } 
    if(checkName(last)) 
    { 
     // valid last name 
    } 
} 

function checkName(name) 
{ 
    var matches = $(regname).val().match(/[^a-zA-Z]/g); 
    if(matches && matches.length > 0) 
    { 
     return true; 
    } else return false; 
} 

希望這會有所幫助。

0

試試這個

/^[A-Za-z]*$/.test(string); 

如果字符串擁有所有的字母則爲true,否則返回false。