yii.activeForm.js 12.9 KB
Newer Older
Qiang Xue committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/**
 * Yii form widget.
 *
 * This is the JavaScript widget used by the yii\widgets\ActiveForm widget.
 *
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
(function ($) {
	
	$.fn.yiiActiveForm = function (method) {
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method ' + method + ' does not exist on jQuery.yiiActiveForm');
			return false;
		}
	};

	var defaults = {
Qiang Xue committed
26 27
		// the jQuery selector for the error summary
		errorSummary: undefined,
Qiang Xue committed
28 29
		// whether to perform validation before submitting the form.
		validateOnSubmit: true,
30 31 32
		// the container CSS class representing the corresponding attribute has validation error
		errorCssClass: 'error',
		// the container CSS class representing the corresponding attribute passes validation
33
		successCssClass: 'success',
34 35
		// the container CSS class representing the corresponding attribute is being validated
		validatingCssClass: 'validating',
Qiang Xue committed
36 37
		// the URL for performing AJAX-based validation. If not set, it will use the the form's action
		validationUrl: undefined,
Qiang Xue committed
38 39 40 41 42
		// a callback that is called before submitting the form. The signature of the callback should be:
		// function ($form) { ...return false to cancel submission...}
		beforeSubmit: undefined,
		// a callback that is called before validating each attribute. The signature of the callback should be:
		// function ($form, attribute, messages) { ...return false to cancel the validation...}
Qiang Xue committed
43
		beforeValidate: undefined,
44 45 46
		// a callback that is called after an attribute is validated. The signature of the callback should be:
		// function ($form, attribute, messages)
		afterValidate: undefined,
Qiang Xue committed
47 48
		// the GET parameter name indicating an AJAX-based validation
		ajaxVar: 'ajax'
Qiang Xue committed
49 50
	};

Qiang Xue committed
51 52 53 54 55 56 57 58 59 60 61 62
	var attributeDefaults = {
		// attribute name or expression (e.g. "[0]content" for tabular input)
		name: undefined,
		// the jQuery selector of the container of the input field
		container: undefined,
		// the jQuery selector of the input field
		input: undefined,
		// the jQuery selector of the error tag
		error: undefined,
		// whether to perform validation when a change is detected on the input
		validateOnChange: false,
		// whether to perform validation when the user is typing.
63
		validateOnType: false,
Qiang Xue committed
64 65 66 67 68 69 70 71 72 73 74 75
		// number of milliseconds that the validation should be delayed when a user is typing in the input field.
		validationDelay: 200,
		// whether to enable AJAX-based validation.
		enableAjaxValidation: false,
		// function (attribute, value, messages), the client-side validation function.
		validate: undefined,
		// status of the input field, 0: empty, not entered before, 1: validated, 2: pending validation, 3: validating
		status: 0,
		// the value of the input
		value: undefined
	};

Qiang Xue committed
76 77 78 79 80 81 82 83
	var methods = {
		init: function (attributes, options) {
			return this.each(function () {
				var $form = $(this);
				if ($form.data('yiiActiveForm')) {
					return;
				}

Qiang Xue committed
84
				var settings = $.extend({}, defaults, options || {});
Qiang Xue committed
85
				if (settings.validationUrl === undefined) {
Qiang Xue committed
86
					settings.validationUrl = $form.prop('action');
Qiang Xue committed
87 88
				}
				$.each(attributes, function (i) {
89
					attributes[i] = $.extend({value: getValue($form, this)}, attributeDefaults, this);
Qiang Xue committed
90 91 92
				});
				$form.data('yiiActiveForm', {
					settings: settings,
Qiang Xue committed
93
					attributes: attributes,
Qiang Xue committed
94 95
					submitting: false,
					validated: false
Qiang Xue committed
96 97
				});

Qiang Xue committed
98
				watchAttributes($form, attributes);
Qiang Xue committed
99

Qiang Xue committed
100
				/**
Qiang Xue committed
101 102
				 * Clean up error status when the form is reset.
				 * Note that $form.on('reset', ...) does work because the "reset" event does not bubble on IE.
Qiang Xue committed
103
				 */
Qiang Xue committed
104
				$form.bind('reset.yiiActiveForm', methods.resetForm);
Qiang Xue committed
105 106

				if (settings.validateOnSubmit) {
Qiang Xue committed
107
					$form.on('mouseup.yiiActiveForm keyup.yiiActiveForm', ':submit', function () {
Qiang Xue committed
108
						$form.data('yiiActiveForm').submitObject = $(this);
Qiang Xue committed
109
					});
Qiang Xue committed
110
					$form.on('submit', methods.submitForm);
Qiang Xue committed
111 112 113 114 115 116 117 118
				}
			});
		},

		destroy: function () {
			return this.each(function () {
				$(window).unbind('.yiiActiveForm');
				$(this).removeData('yiiActiveForm');
119
			});
Qiang Xue committed
120 121
		},

122 123
		data: function() {
			return this.data('yiiActiveForm');
Qiang Xue committed
124 125
		},

Qiang Xue committed
126
		submitForm: function () {
127
			var $form = $(this),
Qiang Xue committed
128 129 130 131 132 133 134 135 136 137
				data = $form.data('yiiActiveForm');
			if (data.validated) {
				// continue submitting the form since validation passes
				return true;
			}

			if (data.settings.timer !== undefined) {
				clearTimeout(data.settings.timer);
			}
			data.submitting = true;
Qiang Xue committed
138
			if (!data.settings.beforeSubmit || data.settings.beforeSubmit($form)) {
Qiang Xue committed
139
				validate($form, function (messages) {
140
					var errors = [];
Qiang Xue committed
141
					$.each(data.attributes, function () {
142 143 144
						if (updateInput($form, this, messages)) {
							errors.push(this.input);
						}
Qiang Xue committed
145 146
					});
					updateSummary($form, messages);
147
					if (errors.length) {
Qiang Xue committed
148 149 150 151 152
						var top = $form.find(errors.join(',')).first().offset().top;
						var wtop = $(window).scrollTop();
						if (top < wtop || top > wtop + $(window).height) {
							$(window).scrollTop(top);
						}
153
					} else {
Qiang Xue committed
154 155 156 157 158 159 160 161
						data.validated = true;
						var $button = data.submitObject || $form.find(':submit:first');
						// TODO: if the submission is caused by "change" event, it will not work
						if ($button.length) {
							$button.click();
						} else {
							// no submit button in the form
							$form.submit();
Qiang Xue committed
162
						}
Qiang Xue committed
163
						return;
Qiang Xue committed
164 165 166 167 168 169 170 171 172 173 174 175
					}
					data.submitting = false;
				}, function () {
					data.submitting = false;
				});
			} else {
				data.submitting = false;
			}
			return false;
		},

		resetForm: function () {
176
			var $form = $(this);
Qiang Xue committed
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
			var data = $form.data('yiiActiveForm');
			// Because we bind directly to a form reset event instead of a reset button (that may not exist),
			// when this function is executed form input values have not been reset yet.
			// Therefore we do the actual reset work through setTimeout.
			setTimeout(function () {
				$.each(data.attributes, function () {
					// Without setTimeout() we would get the input values that are not reset yet.
					this.value = getValue($form, this);
					this.status = 0;
					var $container = $form.find(this.container);
					$container.removeClass(
						data.settings.validatingCssClass + ' ' +
							data.settings.errorCssClass + ' ' +
							data.settings.successCssClass
					);
					$container.find(this.error).html('');
				});
				$form.find(data.settings.summary).hide().find('ul').html('');
			}, 1);
Qiang Xue committed
196 197 198
		}
	};

Qiang Xue committed
199
	var watchAttributes = function ($form, attributes) {
Qiang Xue committed
200
		$.each(attributes, function (i, attribute) {
Qiang Xue committed
201 202
			var $input = findInput($form, attribute);
			if (attribute.validateOnChange) {
Qiang Xue committed
203 204 205 206 207
				$input.on('change.yiiActiveForm', function () {
					validateAttribute($form, attribute, false);
				}).on('blur.yiiActiveForm', function () {
					if (attribute.status == 0 || attribute.status == 1) {
						validateAttribute($form, attribute, !attribute.status);
Qiang Xue committed
208 209
					}
				});
Qiang Xue committed
210
			}
Qiang Xue committed
211
			if (attribute.validateOnType) {
Qiang Xue committed
212 213 214
				$input.on('keyup.yiiActiveForm', function () {
					if (attribute.value !== getValue($form, attribute)) {
						validateAttribute($form, attribute, false);
Qiang Xue committed
215 216 217 218 219 220
					}
				});
			}
		});
	};

Qiang Xue committed
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
	var validateAttribute = function ($form, attribute, forceValidate) {
		var data = $form.data('yiiActiveForm');

		if (forceValidate) {
			attribute.status = 2;
		}
		$.each(data.attributes, function () {
			if (this.value !== getValue($form, this)) {
				this.status = 2;
				forceValidate = true;
			}
		});
		if (!forceValidate) {
			return;
		}

		if (data.settings.timer !== undefined) {
			clearTimeout(data.settings.timer);
		}
		data.settings.timer = setTimeout(function () {
			if (data.submitting || $form.is(':hidden')) {
				return;
			}
Qiang Xue committed
244 245 246 247 248 249 250 251
			$.each(data.attributes, function () {
				if (this.status === 2) {
					this.status = 3;
					$form.find(this.container).addClass(data.settings.validatingCssClass);
				}
			});
			validate($form, function (messages) {
				var hasError = false;
Qiang Xue committed
252
				$.each(data.attributes, function () {
Qiang Xue committed
253 254
					if (this.status === 2 || this.status === 3) {
						hasError = updateInput($form, this, messages) || hasError;
Qiang Xue committed
255 256
					}
				});
Qiang Xue committed
257
			});
Qiang Xue committed
258 259 260
		}, data.settings.validationDelay);
	};
	
Qiang Xue committed
261
	/**
Qiang Xue committed
262 263 264 265
	 * Performs validation.
	 * @param $form jQuery the jquery representation of the form
	 * @param successCallback function the function to be invoked if the validation completes
	 * @param errorCallback function the function to be invoked if the ajax validation request fails
Qiang Xue committed
266
	 */
Qiang Xue committed
267
	var validate = function ($form, successCallback, errorCallback) {
Qiang Xue committed
268
		var data = $form.data('yiiActiveForm'),
Qiang Xue committed
269 270
			needAjaxValidation = false,
			messages = {};
Qiang Xue committed
271 272

		$.each(data.attributes, function () {
Qiang Xue committed
273 274
			if (data.submitting || this.status === 2 || this.status === 3) {
				var msg = [];
Qiang Xue committed
275 276 277 278
				if (!data.settings.beforeValidate || data.settings.beforeValidate($form, this, msg)) {
					if (this.validate) {
						this.validate(this, getValue($form, this), msg);
					}
Qiang Xue committed
279 280
					if (msg.length) {
						messages[this.name] = msg;
Qiang Xue committed
281 282
					} else if (this.enableAjaxValidation) {
						needAjaxValidation = true;
Qiang Xue committed
283 284
					}
				}
Qiang Xue committed
285 286 287
			}
		});

Qiang Xue committed
288
		if (needAjaxValidation && (!data.submitting || $.isEmptyObject(messages))) {
Qiang Xue committed
289 290 291
			// Perform ajax validation when at least one input needs it.
			// If the validation is triggered by form submission, ajax validation
			// should be done only when all inputs pass client validation
Qiang Xue committed
292
			var $button = data.submitObject,
Qiang Xue committed
293 294 295
				extData = '&' + data.settings.ajaxVar + '=' + $form.prop('id');
			if ($button && $button.length && $button.prop('name')) {
				extData += '&' + $button.prop('name') + '=' + $button.prop('value');
Qiang Xue committed
296
			}
Qiang Xue committed
297 298
			$.ajax({
				url: data.settings.validationUrl,
Qiang Xue committed
299
				type: $form.prop('method'),
Qiang Xue committed
300 301 302 303 304 305 306 307 308 309 310 311
				data: $form.serialize() + extData,
				dataType: 'json',
				success: function (msgs) {
					if (msgs !== null && typeof msgs === 'object') {
						$.each(data.attributes, function () {
							if (!this.enableAjaxValidation) {
								delete msgs[this.name];
							}
						});
						successCallback($.extend({}, messages, msgs));
					} else {
						successCallback(messages);
Qiang Xue committed
312
					}
Qiang Xue committed
313 314
				},
				error: errorCallback
Qiang Xue committed
315
			});
Qiang Xue committed
316 317 318 319 320
		} else if (data.submitting) {
			// delay callback so that the form can be submitted without problem
			setTimeout(function () {
				successCallback(messages);
			}, 200);
Qiang Xue committed
321
		} else {
Qiang Xue committed
322
			successCallback(messages);
Qiang Xue committed
323
		}
Qiang Xue committed
324 325 326
	};

	/**
Qiang Xue committed
327
	 * Updates the error message and the input container for a particular attribute.
328
	 * @param $form the form jQuery object
Qiang Xue committed
329 330
	 * @param attribute object the configuration for a particular attribute.
	 * @param messages array the validation error messages
Qiang Xue committed
331 332
	 * @return boolean whether there is a validation error for the specified attribute
	 */
Qiang Xue committed
333 334 335 336
	var updateInput = function ($form, attribute, messages) {
		var data = $form.data('yiiActiveForm'),
			$input = findInput($form, attribute),
			hasError = false;
Qiang Xue committed
337

338 339 340
		if (data.settings.afterValidate) {
			data.settings.afterValidate($form, attribute, messages);
		}
Qiang Xue committed
341 342
		attribute.status = 1;
		if ($input.length) {
Qiang Xue committed
343
			hasError = messages && $.isArray(messages[attribute.name]) && messages[attribute.name].length;
Qiang Xue committed
344
			var $container = $form.find(attribute.container);
Qiang Xue committed
345
			var $error = $container.find(attribute.error);
Qiang Xue committed
346
			if (hasError) {
347
				$error.text(messages[attribute.name][0]);
Qiang Xue committed
348 349 350
				$container.removeClass(data.settings.validatingCssClass + ' ' + data.settings.successCssClass)
					.addClass(data.settings.errorCssClass);
			} else {
351
				$error.text('');
Qiang Xue committed
352 353
				$container.removeClass(data.settings.validatingCssClass + ' ' + data.settings.errorCssClass + ' ')
					.addClass(data.settings.successCssClass);
Qiang Xue committed
354
			}
Qiang Xue committed
355
			attribute.value = getValue($form, attribute);
Qiang Xue committed
356 357 358 359
		}
		return hasError;
	};

Qiang Xue committed
360 361 362 363 364
	/**
	 * Updates the error summary.
	 * @param $form the form jQuery object
	 * @param messages array the validation error messages
	 */
Qiang Xue committed
365 366
	var updateSummary = function ($form, messages) {
		var data = $form.data('yiiActiveForm'),
Qiang Xue committed
367
			$summary = $form.find(data.settings.errorSummary),
368
			$ul = $summary.find('ul').html('');
Qiang Xue committed
369 370 371

		if ($summary.length && messages) {
			$.each(data.attributes, function () {
Qiang Xue committed
372
				if ($.isArray(messages[this.name]) && messages[this.name].length) {
373
					$ul.append($('<li/>').text(messages[this.name][0]));
Qiang Xue committed
374 375
				}
			});
376
			$summary.toggle($ul.find('li').length > 0);
Qiang Xue committed
377
		}
Qiang Xue committed
378 379
	};

Qiang Xue committed
380 381
	var getValue = function ($form, attribute) {
		var $input = findInput($form, attribute);
Qiang Xue committed
382
		var type = $input.prop('type');
Qiang Xue committed
383
		if (type === 'checkbox' || type === 'radio') {
384 385 386 387 388
			var $realInput = $input.filter(':checked');
			if (!$realInput.length) {
				$realInput = $form.find('input[type=hidden][name="'+$input.prop('name')+'"]');
			}
			return $realInput.val();
Qiang Xue committed
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
		} else {
			return $input.val();
		}
	};

	var findInput = function ($form, attribute) {
		var $input = $form.find(attribute.input);
		if ($input.length && $input[0].tagName.toLowerCase() === 'div') {
			// checkbox list or radio list
			return $input.find('input');
		} else {
			return $input;
		}
	};

404
})(window.jQuery);