JQUERYIntermediate

jQuery Form Validation with Tooltip

PB Pb28 Master Team August 22nd, 2022 Intermediate

📦 Get the complete source code for this tutorial

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

html
<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.

javascript
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.

javascript
$(function() {

	$( document ).tooltip({

		position: {my: "left top", at: "right top"},

	  items: "input[required=true], textarea[required=true]",

	  content: function() { return $(this).attr( "title" ); }

	});

});

View Demo

📦 Download the full project files and try it locally