I was wondering if it were possible to force an input field to be an valid email?
<input type="text" name="emailaddress" >
I would like it to use Javascript/JQuery rather than PHP if possible!
Thanks for the help.
I was wondering if it were possible to force an input field to be an valid email?
<input type="text" name="emailaddress" >
I would like it to use Javascript/JQuery rather than PHP if possible!
Thanks for the help.
Support only newer browsers? Try this:
<input type="email" name="emailaddress">
Note that support is somewhat limited, but it might work for you if it falls into these browsers:
http://caniuse.com/#feat=forms
On a related note:
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
You can use the answer @Mike Robinson gave along with some simple validation (found here) as a fallback for older browsers:
HTML:
<input type="email" name="emailaddress" id="valid_email"><div class="validate">Please enter a valid email!</div>
JS:
$('.validate').hide();
$('body').on('blur', '#valid_email', function() {
$('.validate').hide();
if(!isValidEmailAddress($(this).val())) {
$('.validate').show();
}
});
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/i);
return pattern.test(emailAddress);
};
Or, even simpler, you can just use the jQuery Validation Plugin.
You'll also want to validate on the backend, you can do this with PHP filters:
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// do something if email is valid
}
JavaScript cant know if the E-Mail is Valid. (at least in no easy way) To do this in a Dynamic Fashion, you only have the PHP Option. In Javascript you only can Use Ajax to call this with events.
EDIT: To prevent Missunderstanding
Yes you can RegEx, and somewhat with JS. But you only get a Client Side Solution on that. Also a Browser related Test is no real Solution. Validation of Inputs, is about getting the corrent and secure Input. You will only be able, to prevent Users from sending wrong Data, with a PHP framework. Or at least, you use some verry fancy (and i guess expensive) js frameworks, that may protect you.
What if I simply turn off Javascript and use an Old browser so avoid the Validation. Using HTML5 and JavaScript for Validation is only for Usabillity. Not for Security!