• Status: Open
  • Priority: Low
  • Security: Public
  • Views: 44
  • Last Modified:

one validation script for multiple forms

Hello Experts,
I am using one validation file for multiple forms on a page. Code below.
They way that is done is wrong because it validates all the forms on the page all together. So I am trying to identify the form ID and include it to the submit function?
I would be happy if someone can help

$(document).ready(function() {

	"use strict";	

	var form = $('#contactForm, #brochureForm, #enquiryForm, #guideform');	
	
$("input[validate], textarea[validate]").each(function() {
	$(this).on("blur", function() {
			if (($.trim($(this).val() )=== "") || ($.trim($(this).val()).length <= 3)) {
					var errorMsg = $(this).attr('errormessage');
					if (errorMsg === undefined) {
						errorMsg = "Please fill in this field";
					}
				$(this).attr("placeholder", errorMsg);
				$(this).addClass("error");
			} else {
				$(this).removeClass("error");
				$(this).attr("placeholder","");
			}
	});
});	
	
	$(form).on("submit", function(evt) {
		evt.preventDefault();
		if (validate()) {
			submitForm();
		}

	});

	function submitForm() {
		var formData = $(form).serialize();
		$.ajax({
			type: "POST",
			url: "https://url....",
			dataType: "json",
			data: formData,
			complete:function() {
				$(form).hide();
				$(".msgSubmit").show();
			}
		});
	}	
	var validEmail = new RegExp(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);	
	
	// fields validation function
	var validate = function() {
		var requiredInput = $("input[validate], textarea[validate]");
		var result = true;
		
		$(requiredInput).each(function() {
			$(this).removeClass("error");
			$(this).attr("placeholder","");
			
			var validations = $(this).attr("validate").toLowerCase().split(' ');
			for (var i = 0; i < validations.length; ++i) {
				if (validations[i] === "required") {
					if (($.trim($(this).val() )=== "") || ($.trim($(this).val()).length <= 3)) {

						var errorMsg = $(this).attr('errormessage');
						if (errorMsg === undefined) {
							errorMsg = "Please fill in this field"; 
						}
						$(this).attr("placeholder", errorMsg);

						$(this).addClass("error");
						result = false;
					}
				}
				else if (validations[i] === "email") {

					if(!$(this).val().match(validEmail)) {
						result = false;
						$(this).addClass("error");
						$(this).attr("placeholder", "Please enter a valid email address");
					}
				}
			}		
		});
		return result;
	};
});

Open in new window

0
Refael
Asked:
Refael
0 Comments

Join & Write a Comment

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

Tackle projects and never again get stuck behind a technical roadblock.
Join Now