4

I am just learning javascript and jquery, and I must be doing my validation wrong. I have tried a few different ways, and each time, the first alert (test1) fires onblur, but a bad email does not bring up the second alert. I thought about using jquery validation plugin, but after playing with in for a while, I realized that I need validation on each blank onblur, not when it is time to process the form, so I think I am stuck with normal js.

In my document ready function:

$("#studentEmail").blur(function() {
    alert ("test1");
    function validateEmail(studentEmail){  
        var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;  
        if(!emailReg.test(studentEmail)) {
            alert("Please enter valid email id");
        }
    }
});

In my HTML:

<input type="text" class="signUpTextbox" id="studentEmail" name="registerStudentEmail">

Thanks!

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
radleybobins
  • 863
  • 5
  • 10
  • 23
  • Firebug (FF extension) can help you debug problems. Once you install it and bring it up you can open the "Script" tab and set breakpoints, etc. – Jeroen Dec 15 '11 at 15:17

3 Answers3

3

Inside of your blur handler you were declaring a function. Declare your function outside of this handler, and call it inside of your handler.

 function validateEmail(studentEmail){  
     var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;  
     if(!emailReg.test(studentEmail)) {  
         alert("Please enter valid email id");
     }       
 }

 $("#studentEmail").blur(function() { 
    alert ("test1");

    validateEmail($(this).val());
});

Or, if this function has zero reuse you could just do this:

 $("#studentEmail").blur(function() { 
    alert ("test1");

    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;  
    if(!emailReg.test($(this).val())) {  
        alert("Please enter valid email id");
    }        
});
Adam Rackis
  • 82,527
  • 56
  • 270
  • 393
  • Ah, it felt like I wasn't using it properly, and I should be able to do the rest of the validation now. Thanks! I'll mark this as the answer once I'm allowed in 7 mins (low reputation, I think) – radleybobins Dec 15 '11 at 15:19
  • Yeah, its definitely good to see it done both ways. Thanks again! – radleybobins Dec 15 '11 at 16:12
3

Why do you have an inner function here ? This should work

$("#studentEmail").blur(function() { 
    alert ("test1");

    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;  
    if(!emailReg.test(studentEmail)) {  
        alert("Please enter valid email id");
    }       

});
hop
  • 2,518
  • 11
  • 40
  • 56
0
$("#studentEmail").blur(function() { 
    alert ("test1"); 
    function validateEmail(studentEmail){
        var emailReg = /^([\w-.]+@([\w-]+.)+[\w-]{2,4})?$/;
        if(!emailReg.test(studentEmail)) {
            alert("Please enter valid email id");
        }
    }
    // call the validate method
    validateEmail(this.value);
});
Brook
  • 195
  • 8