Advertisement
lalatino

Testing validity for either email or phone

Jul 1st, 2012
321
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <html><head>
  2. <title>http://stackoverflow.com/questions/11285656/how-to-design-two-inputs-in-or-and-logic-for-email-form-with-validation</title>
  3. <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
  4. <script type="text/javascript">
  5. function checkForm(){
  6.     var form = document.forms.form1;
  7.     var hasError = false;
  8.     var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
  9.     var mobileReg = /^[+]?[()/0-9. -]{9,}$/; // see also http://stackoverflow.com/q/5066329/1422309
  10.     var emailaddressVal = form.email.value.replace(/^\s+|\s+$/g,"");
  11.     var mobilenumberVal = form.mobile.value.replace(/^\s+|\s+$/g,"");
  12.     var valid1 = emailReg.test(emailaddressVal);  //email
  13.     var valid2 = mobileReg.test(mobilenumberVal);  //mobile
  14.     if (form.em[0].checked && !valid1) { //invalid email
  15.         $(form.email).parent().next("p").html('<span class="error">Enter a valid email address.</span>');
  16.         hasError = true;
  17.     } else {
  18.         $(form.email).parent().next("p").html('');
  19.     }
  20.     if (form.em[1].checked && !valid2) { // invalid mobile
  21.         $(form.mobile).parent().next("p").html('<span class="error">Enter currect Mobile number.</span>')
  22.         hasError = true;
  23.     } else {
  24.         $(form.mobile).parent().next("p").html('');
  25.     }
  26.     //alert('Error='+hasError +' EmailOk='+ valid1+ ' MobileOk='+ valid2);
  27.     return hasError;
  28. }
  29. </script>
  30. </head><body>
  31. <form name="form1" action="" method="post" onsubmit="return !checkForm()">
  32. <input type="radio" name="em" value="email" /> <label>Email <input type="text" name="email" value="name@server.ext" onclick="this.form.em[0].checked=true" /></label> <p></p><br/>
  33. <input type="radio" name="em" value="mobile" checked="checked" /> <label>Mobile <input type="text" name="mobile" value="1234567890" onclick="this.form.em[1].checked=true" /></label> <p></p><br/>
  34. <input type="submit" name="save_form" value="Send" />
  35. </form>
  36.  
  37. <input type="button" value="test" onclick="checkForm()" />
  38. </body></html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement