2011-10-26 50 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]/; 
相关问题