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