zigil zigil - 5 months ago 9
HTML Question

javascript input validation is not working on the first try

Below is a script on a HTML input form. My problem is that when for the first time I enter something in the input box I get the wrong result, but when I focus on the box again (click in the input box) and then deselect the input box I get the right answer! why this is happening??? what is the solution?

<input type="email" id="iemail" name="email" class="form-control"></input>
<script>
var pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i;
var userinput;
$("#iemail").focus(function(){
userinput = $("#iemail").val();
});
$("#iemail").blur(function(){
if(pattern.test(userinput)){
alert("VALID");
}else{
alert("not a valid e-mail address");
}
});
</script>


could anybody please help me. I will really appreciate it...

Answer

It's because you're assigning a value to userInput on the focus event of the field, which for the first time focus is triggered, when the field is blank, will mean userInput is set to a blank value.

You could move the assignment of userInput to the blur event instead.

var pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i;
$("#iemail").blur(function(){
    var userinput = $("#iemail").val();

    if(pattern.test(userinput)){
        alert("VALID");
    }else{
        alert("not a valid e-mail address");
    }
});