Need help adding minor additional functionality to JQuery Form Validation script

egoselfaxis
egoselfaxis used Ask the Experts™
on
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
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Distinguished Expert 2017

Commented:
Remove line 322 and retry

Author

Commented:
I tried commenting out line # 322 as you suggested and the behavior remains the same.

https://www.evergladesholidaypark.com/ehp-landingpage-markup/
Distinguished Expert 2017
Commented:
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

Author

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,

Author

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

Author

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

- Yvan

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial