jQuery Form Validation with Tooltip

In this tutorial, we are validating a contact form and showing error message by using jQuery tooltip. In a previous tutorial, we have seen an example of jQuery AJAX contact email with form validation.

In this jQuery tooltip example, we are highlighting form fields to show validation results. And then we are calling the tooltip function to show validation messages.

View Demo

Contact Form HTML

This code includes the contact form field required to be validated using jQuery. After validation, these fields are highlighted to show the validation tooltip on mouseover.

jquery-form-tooltip

<div id="frmContact">
	<div id="mail-status"></div>
	<label style="padding-top:20px;">Name</label>
	<div>
	<input type="text" name="userName" id="userName" class="demoInputBox" required="true">
	</div>
	<label>Email</label>
	<div>
	<input type="email" name="userEmail" id="userEmail" class="demoInputBox" required="true">
	</div>
	<label>Subject</label> 
	<div>
	<input type="text" name="subject" id="subject" class="demoInputBox" required="true">
	</div>
	<label>Content</label> 
	<div>
	<textarea name="content" id="content" class="demoInputBox" cols="60" rows="6" required="true"></textarea>
	</div>
	<div>
	<button name="submit" class="btnAction" onClick="sendContact();">Send</button>
	</div>
</div>

jQuery Form Validation

The following script is used to validate the required fields and email. To show the validation result we are applying styles and adding tooltip text messages via jQuery.

function validateContact() {
	var valid = true;
	$("#frmContact input[required=true], #frmContact textarea[required=true]").each(function(){
		$(this).removeClass('invalid');
		$(this).attr('title','');
		if(!$(this).val()){ 
			$(this).addClass('invalid');
			$(this).attr('title','This field is required');
			valid = false;
		}
		if($(this).attr("type")=="email" && !$(this).val().match(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/)){
			$(this).addClass('invalid');
			$(this).attr('title','Enter valid email');
			valid = false;
		}  
	}); 
	return valid;
}

jQuery Tooltip in Form

This jQuery call shows tooltip messages on the mouseover event of the highlighted form fields.

$(function() {
	$( document ).tooltip({
		position: {my: "left top", at: "right top"},
	  items: "input[required=true], textarea[required=true]",
	  content: function() { return $(this).attr( "title" ); }
	});
});

View DemoDownload

Photo of Vincy, PHP developer
Written by Vincy Last updated: August 22, 2022
I'm a PHP developer with 20+ years of experience and a Master's degree in Computer Science. I build and improve production PHP systems for eCommerce, payments, webhooks, and integrations, including legacy upgrades (PHP 5/7 to PHP 8.x).

Leave a Reply

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

Explore topics
Need PHP help?