Dynamic web form validation with predefined rules and messages

Sometimes when we are using same validation rules for a form in different location with different ID’s.

To prevent repeating the code and make it more maintainable we define it as a function in one place.

That is what this blog is about.

Prerequisite

  • jQuery
  • jQuery Validation Plugin

Create a js file

var $postJobValidation = {
	id: function(e) {
		$("#" + e).validate({
			rules: this.rules,
			messages: this.messages
		})
	},
	set: function(e) {

		if (e) {
			for (t in e) {

				if (e[t].rule)
					this.rules[t] = e[t].rule

				if (e[t].message)
					this.messages[t] = e[t].message
			}
		}
	},
	rules: {
		name: "required",
		email: {
			email: !0,
			required: !0
		},
	},
	messages: {
		name: "PLease Enter Your Name",
		email: {
			email: "Enter Valid Email!",
			required: "Enter Email!"
		},
	}
};

To validate a form with id “form1” and having fiels name and email.

$formValidation.id("form1")

To add rules and message we just need to edit rules and message object in $formValidation

$postJobValidation.set({
	"contact": {
		rule: "required",
		message: "Please Enter Your Contact"
	}
})

Set function iterates through the json provided and adding rules

Leave a Reply

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