Having a contact form in a website, I wanted to prevented in an easy way, and as much as possible, the user to enter an invalid e-mail address. I first thought using regular expression within the PHP script but then would be better to display the error message on the form without reloading the page so I’ve choosen JavaScript.
function checkForm(form) { var emailFormat = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i; if (form.email.value == "") { document.getElementById('check').innerHTML = "Please fill in your e-mail."; form.email.focus(); return false ; } else if (form.email.value.search(emailFormat) == -1) { document.getElementById('check').innerHTML = "Please fill in a valid e-mail."; form.email.focus(); return false ; } return true; }
The regular expression used will accept a normal e-mail format like foo@bar.com as well as something like foo_bar23@foo-bar19.com
That piece of code is part of a bigger JavaScript function where other statements check the other fields of the form in case they have null values. If the return boolean is false then the form is not submitted and the appropriate error message is displayed.