我有一個個人函數誰採取一個id和模式來檢查一些輸入。發送模式到函數
var id, schema;
\t function checkField(id, schema){
\t \t var input = id.val();
\t \t var pattern = schema;
\t \t if (!input.match(pattern)){
\t \t \t console.log('Input = '+input);
\t \t \t console.log('Pattern = '+pattern);
\t \t \t id.removeClass().addClass("error");
\t \t \t $(".oke").css({display: 'none'});
\t \t }else{
\t \t \t console.log('Classe = ok');
\t \t \t id.removeClass().addClass("ok");
\t \t \t $(".nope").css({display: 'none'});
\t \t }
\t }
\t // Vérification téléphone
\t $("#tel").focusout(function(){
\t \t checkField($(this), "/0[1-7,9]\d{8}/");
\t });
\t // Vérification code postale
\t $("#cp").focusout(function(){
\t \t checkField($(this), "/^((0[1-9])|([1-8][0-9])|(9[0-8])|(2A)|(2B))[0-9]{3}$/");
\t });
但如果條件始終返回null
(!input.match(pattern)
)。 兩個控制檯日誌返回輸入中寫入的數字,並且模式正確,爲什麼if總是爲false?
雙引號必須從各地正則表達式被刪除,第一個可能還需要錨('/^0 [1-79] \ d {8} $ /')。第二個可以寫成'/ ^(0 [1-9] | [1-8] \ d | 9 [0-8] | 2 [AB])\ d {3} $ /'。另外,建議用if(!pattern.test(input))替換'if(!input.match(pattern))'' –
非常感謝:) input.match pattern和pattern.test輸入? – Buck
'test()'返回* true *或* false *,而'match'將返回* null *或匹配數據數組。 –