2

I have a form that is being generated dynamically with PHP.

There's are multiple fields for email. I would like to conduct a very basic email validation when the form loads with the data pre-filled. Those fields that contain malformed emails need to be highlighted and form submission disabled.

Here's what I've got so far, but I'm not sure how to get it all to work.

JS

function validateEmail(email) {
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    return emailReg.test( email );
}

$("#mySubmitButton").click(function() {
    var email = jQuery("input[name=\'email[]\']").val();
    if (!validateEmail(email)) {
        event.preventDefault();
        $(this).css("border","1px solid red");
        alert("Bad email. Please correct before submitting.");
    }
});  

PHP

$pairs = array_filter(explode(",", $_POST['email']));

foreach( $pairs as $pair ) {


   $i++;

   echo '<input type="text" name="email['.$i.']" value="'.$output['1'].'">

}
santa
  • 12,234
  • 49
  • 155
  • 255
  • Email addresses are allowed to include `+` characters. TLDs can have more than 4 characters in them. – Quentin May 21 '12 at 15:40

2 Answers2

3

You can validate all emails like this

jQuery("input[type=text][name^=email]").each(function()
{
  if(!validateEmail($(this).val()))
  {
    alert("Email not validated,");
    //here you can figure out the invalid emails
  }
});
Adil
  • 146,340
  • 25
  • 209
  • 204
  • So, OK, I can mark "bad" emails. How do I disable submit though? Also if I have a number of bad email, I don't really want to show an alert for each one. It would be sufficient to do it once on submit attempt. – santa May 21 '12 at 16:17
0
var email = jQuery("input[type=text][name^=email]").val();

[name^=email] will select all input named start with email and type of text.

See here for detail

Fro email validation check here

Community
  • 1
  • 1
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164