jQuery Form Validation with Tooltip

by Vincy. Last modified on August 22nd, 2022.

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

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

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

↑ Back to Top

Share this page