Enable Disable Submit Button Based on Validation

by Vincy. Last modified on July 12th, 2022.

Now we are going to see about how to enable or disable form submit button based on the form validation result. In a previous example, we have seen form validation using PHP on clicking submit button.

We have an example with an HTML form with disabled submit button. And then, we are enabling it by validating form fields using jQuery.

View Demo

HTML Form With Disabled Submit Button

This code shows the HTML form in which the submit button is disabled initially.

enable-disable-form-submit

<form id="frm" method="post">
   <div class="input-group">Name <span class="name-validation validation-error"></span></div>
   <div>
        <input type="text" name="name" id="name" class="input-control" onblur="validate()" />
   </div>
    
   <div class="input-group">Email <span class="email-validation validation-error"></span></div>
   <div>
		<input type="text" name="email" id="email" class="input-control" onblur="validate()" />
   </div>

   <div>
        <button type="submit" name="btn-submit" id="btn-submit" disabled="disabled">Submit</button>
    </div>
</form>

jQuery Validation to Enable / Disable Submit Button

This jQuery script validates the text input fields name and email. It checks if the both fields are not empty. And also check if the email field is containing valid email address by using a regex pattern. Once, the form is validated then it returns true to enable submit button.

<script>
	function validate() {
		
		var valid = true;
		valid = checkEmpty($("#name"));
		valid = valid && checkEmail($("#email"));
		
		$("#btn-submit").attr("disabled",true);
		if(valid) {
			$("#btn-submit").attr("disabled",false);
		}	
	}
	function checkEmpty(obj) {
		var name = $(obj).attr("name");
		$("."+name+"-validation").html("");	
		$(obj).css("border","");
		if($(obj).val() == "") {
			$(obj).css("border","#FF0000 1px solid");
			$("."+name+"-validation").html("Required");
			return false;
		}
		
		return true;	
	}
	function checkEmail(obj) {
		var result = true;
		
		var name = $(obj).attr("name");
		$("."+name+"-validation").html("");	
		$(obj).css("border","");
		
		result = checkEmpty(obj);
		
		if(!result) {
			$(obj).css("border","#FF0000 1px solid");
			$("."+name+"-validation").html("Required");
			return false;
		}
		
		var email_regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,3})+$/;
		result = email_regex.test($(obj).val());
		
		if(!result) {
			$(obj).css("border","#FF0000 1px solid");
			$("."+name+"-validation").html("Invalid");
			return false;
		}
		
		return result;	
	}
</script>

View DemoDownload

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page