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'].'">

}
1
  • Email addresses are allowed to include + characters. TLDs can have more than 4 characters in them. Commented May 21, 2012 at 15:40

2 Answers 2

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
  }
});
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.