Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submit the form only if email is valid

Tags:

javascript

I need a way to submit a form only if email is valid. If email is NOT valid then show ONLY an alert ( below you can see my code ).

JAVASCRIPT:

 function validateEmail(email) { 
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
 } 


 function continueornot() {
    if(validateEmail(document.getElementById('emailfield').value)){
    // ok
    }else{ alert("email not valid"); return false;}
 }

HTML:

<form method="post" action="register.php" enctype="multipart/form-data">
<table>
<tr><td>Email:</td></tr>
<tr><td><input type="text" size="30" name="email" id="emailfield"> </td></tr>
<tr><td>Password:</td></tr>
<tr><td><input type="password" size="30" name="password"> </td></tr>
</table>
<input name="steptwo" value="Create Account" type="submit" onclick="continueornot();"/>
</form>

The problem is that the form is submitted even if the email is NOT valid.

How can I resolve this problem ?

like image 737
xRobot Avatar asked Oct 17 '25 01:10

xRobot


2 Answers

You should attach return continueornot(); to the onsubmit event of the form, not the button's click event.

See this fiddle: http://jsfiddle.net/NdSmu/

like image 92
moribvndvs Avatar answered Oct 18 '25 14:10

moribvndvs


You need the return value.

function continueornot() {
    if(validateEmail(document.getElementById('emailfield').value)){
      // ok
      return true;
    }else{ alert("email not valid"); return false;}
 }


onclick="return continueornot();"
like image 29
xdazz Avatar answered Oct 18 '25 14:10

xdazz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!