Original javascript validation javascript not validated

I am just learning javascript and jquery and I should be wrong in my validation. I tried several different ways, and each time the first warning (test1) fires onblur, but a bad letter does not cause a second warning. I thought about using the jquery validation plugin, but after some time of the game I realized that I need to check the correctness of each empty onblur, and not when it is time to process the form, so I think I'm stuck with regular js.

In my finished documentation:

$("#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!

+4
source share
3 answers

Inside your blur handler, you declare a function. Declare your function outside this handler and call it inside 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 can simply 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"); } }); 
+3
source

Why do you have an internal 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"); } }); 
+3
source
 $("#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); }); 
0
source

Source: https://habr.com/ru/post/1386540/


All Articles