2011-10-26 48 views
1

我嘗試使用jQuery在正則表達式驗證程序失敗時更改文本框顏色。在驗證失敗時使用JQuery更改文本框顏色

這是我在網上找到的一個功能,但我不知道如何改變它來使用正則表達式。

<script type="text/javascript"> 
    function ValidateTextBox(source, args) 
    { 
     var is_valid = $("#TextBox1").val() != ""; 
     $("#TextBox1").css("background-color", is_valid ? "white" : "red"); 
     args.IsValid = is_valid; 
    } 
</script> 

另外,我不明白什麼用的

args.IsValid = is_valid; 

在函數。


這是我現在想:

<script type="text/javascript"> 
function ValidateTextBox(source, args) { 
    var is_valid = false; 

    //Regex goes here 
    var regex = [A-Za-z]; 
    if (regex.test($('#TextBox1').val())) { 
     //If input was correct 
     is_valid = true; 
    } 
    else { 
     //If input is not correct 
     $("#TextBox1").css("background-color" : "red");   
    } 
    args.IsValid = is_valid; //Returns validity state 
} 


</script> 

回答

0
function ValidateTextBox(source, args) 
{ 
    //var is_valid = $("#TextBox1").val() != ""; //returns true or false 

    //add regex test, lots of way and set result to is_valid 
    var is_valid = false; 
    var rege = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; //example 
    if(rege.test($('#TextBox1').val())){ 
     is_valid = true; 
    } 

    $("#TextBox1").css("background-color", is_valid ? "white" : "red"); 
    args.IsValid = is_valid; //tells validatin engine if this item is valid or not 
} 
+0

有些事情我不明白。 var is_valid = $(「#TextBox1」)。val() 不應該是源代替#TextBox1?由於source是調用事件的對象。 另外,我在哪裏鍵入正則表達式?我真的很新的JavaScript。 – TheGateKeeper

+0

rege變量具有正則表達式。 $(「#TextBox1」)。val()是jQuery如何檢查元素的值。 –

+0

另請參閱:http://stackoverflow.com/q/201323/901048 – Blazemonger

0

JavaScript的正則表達式需要用//這樣的包圍。

//Regex goes here 
var regex = /[A-Za-z]/; 
相關問題