Validating email address field

Hi there,

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.

This is the code I have:

<script>
	$(document).ready(function (e){
		$("#frmContact").on('submit',(function(e){
			e.preventDefault();
			$("#mail-status").hide();
			$('#send-message').hide();
			$('#loader-icon').show();
			$.ajax({
				url: "contact.php",
				type: "POST",
				dataType:'json',
				data: {
				"name":$('input[name="name"]').val(),
				"email":$('input[name="email"]').val(),
				"phone":$('input[name="phone"]').val(),
				"content":$('textarea[name="content"]').val(),
				"g-recaptcha-response":$('textarea[id="g-recaptcha-response"]').val()},				
				success: function(response){
				$("#mail-status").show();
				$('#loader-icon').hide();
				if(response.type == "error") {
					$('#send-message').show();
					$("#mail-status").attr("class","error");				
				} else if(response.type == "message"){
					$('#send-message').hide();
					$("#mail-status").attr("class","success");							
				}
				$("#mail-status").html(response.text);	
				},
				error: function(){} 
			});
		}));
	});
	</script>

Can anyone suggest a way of making sure the email address entered is an actual email?

Thanks

You could have a look at this page on form validation. The start point is ensuring you have your email input box set to the correct type in your HTML.

3 Likes

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.

1 Like

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:

function isValidEmail (value) {
  const input = document.createElement('input')

  input.type = 'email'
  input.value = value

  return input.validity.valid
}

console.log(
  isValidEmail('foo'),        // false
  isValidEmail('bar@baz.net') // true
)

(Basically the same trick as using a virtual anchor element as an URL parser…)

2 Likes