I have a two field HTML form for newsletter signup. One field is for first name the other is for email.
I want to validate for both fields being entered, and also for the email address being valid.
I am a relative beginner but have borrowed code, read, researched, watched videos and played around but the best I have been able to achieve is the email validation which I borrowed from www.w3schools.com.
The code I have in my Wordpress header.php file is
<script type="text/javascript">
function validateForm() {
var x=document.forms["newslettersignup"]["bm_email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+1>=x.length)
{
alert("Please enter a valid e-mail address");
return false;
}
}
</script>
and the code in the body of the Wordpress pages where I want the form to display is
<form name="newslettersignup" action="/wp-content/plugins/pommo/user/process.php" onsubmit="return validateForm()" method="POST">
Name<input type="text" class="text" style="width: 150px;" name="d[1]" id="d[1]"/>
Email<input type="text" class="text" style="width: 150px;" name="bm_email" id="bm_email" value="" />
</form>
Whatever I have tried with regards to adding empty field validation for the two fields stops the above working. When I have it just as it is above the alert works perfectly.
Is this a Wordpress thing stopping me from using any of the numerous examples on the net for validating multiple fields?
Thanks for the help.
Wordpress comes with jQuery so I would use that for your form validation instead. jQuery is javascript, but its syntax is easier to follow and it also helps to normalize between different browser versions. Here is an example for your use case:
http://jsfiddle.net/khVtB/
jQuery also has an awesome validation plugin that will do a lot of these hard things for you.
If you require a non-jQuery solution then I can help with that too, but I think this is probably a better way to go. I can assure you that Wordpress isn't stopping your validation. If anything there may be a script error. You can see this by bringing up your browsers developer tools. For example Firebug in FF, or pressing F12 in Chrome or IE9.
I just reread your question and it looks like you posted your working code and not your non-working code. Hard to debug without seeing the nonworking code. Here is how I would check for empty fields in your javascript solution.