jero3
jero3

Reputation: 13

javascript validation email address not respond

juse have a quick question, i have try to do the validation for email address. i need to do a validation such as validate if an email address is a school email(which means end with edu), but i decide to start from validate the normal email, the code below is what i have down.

Javascript part

function ok_Email(email){
    var filter = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    if(filter.test(email)){
        return true;
        window.alert('This is an email')
    }
else{
    return false;
    window.alert('This is not an email')
}
}

Html part

<form name="myform"
onSubmit="return ok_Email(this);">
<p>
Please enter your email address: <br>
<input type="text" size=40 name="user_email">
<p>
<input type = submit value="Send">
</form>

The problem for this code is when i click the send buttom, the page did not change. As you see in the code, it should have an alert comes out but it doesn't. I think the problem comes from the buttom part but i am not sure.......

Upvotes: 0

Views: 56

Answers (2)

Aditya Vikas Devarapalli
Aditya Vikas Devarapalli

Reputation: 3473

you need to change your code to this :

function ok_Email(form.user_email.value){
    var filter = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    if(filter.test(foam.user_email.value)){
        window.alert('This is an email');
        return true;
    }
    else{
      window.alert('This is not an email');
      return false;
    }
}

to see the alert boxes and also to pass the value of the Email field

Upvotes: 0

epascarello
epascarello

Reputation: 207501

The alerts do not appear because the returns are before the alert! The code exits at that point and nothing after it will execute.

Second issue is you are testing the regular expression against an object.

"return ok_Email(this);">
                 ^^^^
                  this is the form

 function ok_Email(email){
                   ^^^^^
                   You think it is a string

You need to be referencing the value of user_email.

function ok_Email(form){
    var email = form.user_email.value;

Upvotes: 3

Related Questions