1

I'm trying to use jQuery to alter the textbox color, when a regex validator fails.

Here is a function I found online, but I don't know how to alter it to use regex.

<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>

Also, I don't understand what the use of

args.IsValid = is_valid;

Is in the function.


Here is what I am trying now:

<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>
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
TheGateKeeper
  • 4,420
  • 19
  • 66
  • 101

2 Answers2

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
}
rick schott
  • 21,012
  • 5
  • 52
  • 81
  • Some things i dont understand. var is_valid = $("#TextBox1").val() Shouldnt it be source instead of #TextBox1? Since source is the object calling the event. Also, where do i type the regex? Im really new to javascript. – TheGateKeeper Oct 26 '11 at 19:36
  • The rege variable has the regular expression. $("#TextBox1").val() is how jQuery checks the value of an element. – rick schott Oct 26 '11 at 19:40
  • Ok i think i understand the function, just one thing i am still confused about. Where you use the "rege.test" method, it will set is_valid to true if the input is correct right? otherwise it changes the background color? Shouldnt there be an else there? – TheGateKeeper Oct 26 '11 at 20:32
0

JavaScript regex needs to be surrounded by // like this.

//Regex goes here
var regex = /[A-Za-z]/;
Narendra Yadala
  • 9,554
  • 1
  • 28
  • 43