2014-11-03 37 views
2

我是JavaScript新手,很難寫一個條件語句,如果輸入字段爲空/空白或包含除了a-z之外的任何其他字符,則會給出錯誤。如何編寫'if'語句以便不允許輸入字段中的空格?

這是我到目前爲止有:

$(document).ready(function(){ 
$('input#first, #city, #subject, input#last, textarea#message').on("keyup bind cut copy paste", function(){ 
    var value = $(this).val(); 
    var first = new RegExp('[a-z]'); 
    if (/^\s*$/.test(first.value)); 
    if(value=='' || first.length<=1) { 
    if(value=='' || last.length<=1); 
    if(value=='' || city.length<=1); 
    if (first.test(value)); 
    $(this).css('border','2px solid #ff0000'); 
    $(this).css('background-color','#ffcece'); 
    } 
    else { 
    $(this).css('border','1px solid #ffd09d'); 
    $(this).css('background-color','#ffffff'); 
    } 
}); 
}); 
+0

你想只使用HTML5表格驗證?它不適用於一些舊的瀏覽器,但是你會爲自己節省很多頭痛。 – 2014-11-03 20:27:49

+0

我寧願使用JavaScript,所以我可以嘗試並學習它。 – Marlon 2014-11-03 20:29:54

+0

你有錯誤信息嗎? – ianaya89 2014-11-03 20:32:22

回答

1

這應該爲你工作

$(document).ready(function(){ 
$('input#first, #city, #subject, input#last, textarea#message').on("keyup bind cut copy paste", 
function(){ 
    var value = $(this).val(); 
    var first = new RegExp('^[a-zA-Z]+$'); 
    if (first.test(value)) { 
     $(this).css('border','2px solid #ff0000'); 
     $(this).css('background-color','#ffcece'); 
    } 
    else { 
     $(this).css('border','1px solid #ffd09d'); 
     $(this).css('background-color','#ffffff'); 
    } 
}); 
}); 
+0

也許它應該是a-zA-Z(或者一個無聲的標誌)? – 2014-11-03 20:34:49

+0

這是一個很好的觀點,我只是在複製OP正則表達式,但你說得對,那可能是一個錯誤。我做了改變。 – Shriike 2014-11-03 20:35:41

+1

我在else語句中出現語法錯誤。 – Marlon 2014-11-03 21:46:24

0

嘗試這樣:

document.getElementById("yourInputPanel").addEventListener("onchange",function(){ 

    if(document.getElementById("yourInputPanel").search(" ") > -1){ 
    ... 
    Handling Code 
    ... 
    } 

});