I have a form that validates some fields, but I can’t work out how to validate an email field. At the moment, the email field is required, but doesn’t validate if it’s an actual email address.
You could either put it as an attribute in the HTML input tag such as type="email" or you could take the id tag of the field and validate it with JS. Something like:
if ($("#frmContact").length > 0) {
$("#frmContact").validate({
rules: {
name: {
required: true,
maxlength: 50
},
contact_no: {
required: true,
digits:true,
minlength: 10,
maxlength:12,
},
email: {
required: true,
maxlength: 50,
email: true,
},
},
messages: {
name: {
required: "Please enter your full name",
maxlength: "Your name cannot be more than 50 characters long."
},
contact_no: {
required: "Please enter contact number",
minlength: "The contact number should be 10 digits",
digits: "Please enter only numbers",
maxlength: "The contact number should be 12 digits",
},
email: {
required: "Please enter valid email",
email: "Please enter valid email",
maxlength: "The email name should less than or equal to 50 characters",
},
},
submitHandler: function(form) {
$.ajax......
I would just use type=“email” which ensures that the webpage refuses to issue the submit event until the email is appropriately formatted.
<input type="email" name="email" required>
And, on the server side use standard techniques for validating the email, such as sending a confirmation email where the user clicks a link to confirm that their email is correct.
Is there any good reason at this stage to do things any other way?
Validating an email ‘strictly properly’ is an extremely difficult proposition. It’s usually down to ‘do enough that you’re satisfied’, or, as has already been suggested, accept what the browser thinks qualifies as an email.
According to the actual standards for email, \ @a-z is a legal email address. Have fun with that one.
As already noted, the easiest and probably most robust way to validate an email address is by adding type="email" to your input field. And you can still take advantage of the constraint validation API to validate any string by creating an input element in memory only: