• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 41
  • Last Modified:

Need help adding minor additional functionality to JQuery Form Validation script

I have a web form on this page that's using jQuery based form field validation:

https://www.evergladesholidaypark.com/ehp-landingpage-markup/

Here's a link to the JS file that contains the validation script(s):

https://www.evergladesholidaypark.com/ehp-landingpage-markup/js/jquery.main.js

On the form .. I have the following DIV which is currently hidden by default:

<div class="error-message">            
You have either left one or more of the required fields in the form blank, or filled them out incorrectly.  Please apply the necessary corrections before re-submitting then form.            
</div>

Open in new window


Right now .. if you just click on the submit button without filling in any of the fields, .. the .error-message DIV is displayed for about 3 seconds, and then fades out.  I'm doing that using this code snippet which starts at about line number 305 in the JS file:

if (success != true) {          
  $(".error-message").show().delay(3000).fadeOut( "slow");          
}

Open in new window


The problem, however, is that I've placed this code inside the "checkSuccess" handler --- which is also being fired whenever an "onChange" event is triggered by any of the form fields.  This is obviously resulting in undesired effect .. where the error message repeatedly gets displayed adn then fades out, ... making the page grow and then shrink repeatedly.

What I'd like to do is change the script so that the .error-message DIV is only displayed when the following rules are met:

1) The submit button has been clicked.
2) One or more of the required fields in the form has failed the validation

In other words, .. I'd like to disassociate the showing of the .error-message DIV from the onChange events that are triggered by interacting with the form fields.

How would I do that?  And how can I also force the immediate hiding of that .error-message DIV when the submit button is clicked and all of the validation rules have been met (in addition to actually submitting the form)?

Thanks,
- Yvan
0
egoselfaxis
Asked:
egoselfaxis
  • 4
  • 2
1 Solution
 
Leonidas DosasCommented:
Remove line 322 and retry
0
 
egoselfaxisAuthor Commented:
I tried commenting out line # 322 as you suggested and the behavior remains the same.

https://www.evergladesholidaypark.com/ehp-landingpage-markup/
0
 
Leonidas DosasCommented:
Replace the lines from 039 till 357 with this and retry.
;(function($) {
	'use strict';
    var flag;
	var FormValidation = (function() {
		var Validator = function($field, $fields) {
			this.$field = $field;
			this.$fields = $fields;
		};

		Validator.prototype = {
			reg: {
				email: '^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$',
				number: '^[0-9]+$', 
        tel: '^[0-9]+$'
			},

			checkField: function() {
				return {
					state: this.run(),
					$fields: this.$field.add(this.additionalFields)
				}
			},

			run: function() {
				var fieldType;

				switch (this.$field.get(0).tagName.toUpperCase()) {
					case 'SELECT':
						fieldType = 'select';
						break;

					case 'TEXTAREA':
						fieldType = 'text';
						break;     

					default:
						fieldType = this.$field.data('type') || this.$field.attr('type');
				}

				var functionName = 'check_' + fieldType;
				var state = true;

				if ($.isFunction(this[functionName])) {
					state = this[functionName]();

					if (state && this.$field.data('confirm')) {
						state = this.check_confirm();
					}
				}

				return state;
			},
      
 			check_tel: function() {
				var value = this.getValue();
				var required = this.$field.data('required');
				var requiredOrValue = required || value.length;

				if ((requiredOrValue && !this.check_regexp(value, this.reg.tel))) {
					return false;
				}

				return requiredOrValue ? true : null;
			},     

			check_email: function() {
				var value = this.getValue();
				var required = this.$field.data('required');
				var requiredOrValue = required || value.length;

				if ((requiredOrValue && !this.check_regexp(value, this.reg.email))) {
					return false;
				}

				return requiredOrValue ? true : null;
			},

			check_number: function() {
				var value = this.getValue();
				var required = this.$field.data('required');
				var isNumber = this.check_regexp(value, this.reg.number);
				var requiredOrValue = required || value.length;

				if (requiredOrValue && !isNumber) {
					return false;
				}

				var min = this.$field.data('min');
				var max = this.$field.data('max');
				value = +value;

				if ((min && (value < min || !isNumber)) || (max && (value > max || !isNumber))) {
					return false;
				}

				return (requiredOrValue || min || max) ? true : null;
			},

			check_password: function() {
				return this.check_text();
			},

			check_text: function() {
				var value = this.getValue();
				var required = this.$field.data('required');

				if (this.$field.data('required') && !value.length) {
					return false;
				}

				var min = +this.$field.data('min');
				var max = +this.$field.data('max');

				if ((min && value.length < min) || (max && value.length > max)) {
					return false;
				}

				var regExp = this.$field.data('regexp');

				if (regExp && !this.check_regexp(value, regExp)) {
					return false;
				}

				return (required || min || max || regExp) ? true : null;
			},

			check_confirm: function() {
				var value = this.getValue();
				var $confirmFields = this.$fields.filter('[data-confirm="' + this.$field.data('confirm') + '"]');
				var confirmState = true;

				for (var i = $confirmFields.length - 1; i >= 0; i--) {
					if ($confirmFields.eq(i).val() !== value || !value.length) {
						confirmState = false;
						break;
					}
				}

				this.additionalFields = $confirmFields;

				return confirmState;
			},

			check_select: function() {
				var required = this.$field.data('required');

				if (required && this.$field.get(0).selectedIndex === 0) {
					return false;
				}

				return required ? true : null;
			},

			check_radio: function() {
				var $fields = this.$fields.filter('[name="' + this.$field.attr('name') + '"]');
				var required = this.$field.data('required');

				if (required && !$fields.filter(':checked').length) {
					return false;
				}

				this.additionalFields = $fields;

				return required ? true : null;
			},

			check_checkbox: function() {
				var required = this.$field.data('required');

				if (required && !this.$field.prop('checked')) {
					return false;
				}

				return required ? true : null;
			},

			check_at_least_one: function() {
				var $fields = this.$fields.filter('[data-name="' + this.$field.data('name') + '"]');

				if (!$fields.filter(':checked').length) {
					return false;
				}

				this.additionalFields = $fields;

				return true;
			},

			check_regexp: function(val, exp) {
				return new RegExp(exp).test(val);
			},

			getValue: function() {
				if (this.$field.data('trim')) {
					this.$field.val($.trim(this.$field.val()));
				}

				return this.$field.val();
			}
		};

		var publicClass = function(form, options) {
			this.$form = $(form).attr('novalidate', 'novalidate');
			this.options = options;
		};

		publicClass.prototype = {
			buildSelector: function(input) {
				return ':input:not(' + this.options.skipDefaultFields + (this.options.skipFields ? ',' + this.options.skipFields : '') + ')';
			},

			init: function() {
				this.fieldsSelector = this.buildSelector(':input');

				this.$form
					.on('submit', this.submitHandler.bind(this))
					.on('keyup blur', this.fieldsSelector, this.changeHandler.bind(this))
					.on('change', this.buildSelector('select'), this.changeHandler.bind(this))
					.on('focus', this.fieldsSelector, this.focusHandler.bind(this));
			},

			submitHandler: function(e) {
				flag=true
				var self = this;
				var $fields = this.getFormFields();

				this.getClassTarget($fields)
				    .removeClass(this.options.errorClass + ' ' + this.options.successClass); 

				this.setFormState(true);

				$fields.each(function(i, input) {
					var $field = $(input);
					var $classTarget = self.getClassTarget($field);

					// continue iteration if $field has error class already
					if ($classTarget.hasClass(self.options.errorClass)) {
						return;
					}

					self.setState(new Validator($field, $fields).checkField());
				});
        
				return this.checkSuccess($fields, e);
        
			},

			checkSuccess: function($fields, e) {
				var self = this;
				var success = this.getClassTarget($fields || this.getFormFields())
								  .filter('.' + this.options.errorClass).length === 0;                     

				if (e && success && this.options.successSendClass) {
					e.preventDefault(); 
          
					$.ajax({
						url: this.$form.removeClass(this.options.successSendClass).attr('action') || '/',
						type: this.$form.attr('method') || 'POST',
						data: this.$form.serialize(),
						success: function() {
							self.$form.addClass(self.options.successSendClass);
              $(".error-message").hide();
						}
					});          
          
        }        
        
        if (success != true && flag!==true) {          
          $(".error-message").show().delay(3000).fadeOut( "slow");          
        }

				this.setFormState(success); 

				return success;       
        
			},

			changeHandler: function(e) {
				var $field = $(e.target);

				if ($field.data('interactive')) {
					this.setState(new Validator($field, this.getFormFields()).checkField());
				}

				this.checkSuccess();
			},

			focusHandler: function(e) {
				var $field = $(e.target);

				this.getClassTarget($field)
					.removeClass(this.options.errorClass + ' ' + this.options.successClass);

				this.checkSuccess();
			},

			setState: function(result) {
				this.getClassTarget(result.$fields)
					.toggleClass(this.options.errorClass, result.state !== null && !result.state)
					.toggleClass(this.options.successClass, result.state !== null && this.options.successClass && !!result.state);
			},

			setFormState: function(state) {
				if (this.options.errorFormClass) {
					this.$form.toggleClass(this.options.errorFormClass, !state);
				}
			},

			getClassTarget: function($input) {
				return (this.options.addClassToParent ? $input.closest(this.options.addClassToParent) : $input);
			},

			getFormFields: function() {
				return this.$form.find(this.fieldsSelector);
			}
		};

		return publicClass;
	}());

Open in new window

0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

 
egoselfaxisAuthor Commented:
This code replacement doesn't display my .error-class DIV at all.

https://www.evergladesholidaypark.com/ehp-landingpage-markup/

I appreciate your help by the way,
0
 
egoselfaxisAuthor Commented:
Leonidas .. I just discovered that there's some additional form field validation going on inside this other JS file:

https://www.evergladesholidaypark.com/ehp-landingpage-markup/js/script.js

I'm examining and revising this other script it as we speak.  

My apologies .. I wasn't aware of this until just now.  I'll post a followup once I've made some progress.

- Yvan
0
 
egoselfaxisAuthor Commented:
Thanks Leonidas.  Obviously I'm going to need to consolidate my 2 different JS files somehow.  

- Yvan
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

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