1/** 2 * Yii form widget. 3 * 4 * This is the JavaScript widget used by the yii\widgets\ActiveForm widget. 5 * 6 * @link http://www.yiiframework.com/ 7 * @copyright Copyright (c) 2008 Yii Software LLC 8 * @license http://www.yiiframework.com/license/ 9 * @author Qiang Xue <[email protected]> 10 * @since 2.0 11 */ 12(function ($) { 13 14 $.fn.yiiActiveForm = function (method) { 15 if (methods[method]) { 16 return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); 17 } else { 18 if (typeof method === 'object' || !method) { 19 return methods.init.apply(this, arguments); 20 } else { 21 $.error('Method ' + method + ' does not exist on jQuery.yiiActiveForm'); 22 return false; 23 } 24 } 25 }; 26 27 var events = { 28 /** 29 * beforeValidate event is triggered before validating the whole form. 30 * The signature of the event handler should be: 31 * function (event, messages, deferreds) 32 * where 33 * - event: an Event object. 34 * - messages: an associative array with keys being attribute IDs and values being error message arrays 35 * for the corresponding attributes. 36 * - deferreds: an array of Deferred objects. You can use deferreds.add(callback) to add a new deferred validation. 37 * 38 * If the handler returns a boolean false, it will stop further form validation after this event. And as 39 * a result, afterValidate event will not be triggered. 40 */ 41 beforeValidate: 'beforeValidate', 42 /** 43 * afterValidate event is triggered after validating the whole form. 44 * The signature of the event handler should be: 45 * function (event, messages, errorAttributes) 46 * where 47 * - event: an Event object. 48 * - messages: an associative array with keys being attribute IDs and values being error message arrays 49 * for the corresponding attributes. 50 * - errorAttributes: an array of attributes that have validation errors. Please refer to attributeDefaults for the structure of this parameter. 51 */ 52 afterValidate: 'afterValidate', 53 /** 54 * beforeValidateAttribute event is triggered before validating an attribute. 55 * The signature of the event handler should be: 56 * function (event, attribute, messages, deferreds) 57 * where 58 * - event: an Event object. 59 * - attribute: the attribute to be validated. Please refer to attributeDefaults for the structure of this parameter. 60 * - messages: an array to which you can add validation error messages for the specified attribute. 61 * - deferreds: an array of Deferred objects. You can use deferreds.add(callback) to add a new deferred validation. 62 * 63 * If the handler returns a boolean false, it will stop further validation of the specified attribute. 64 * And as a result, afterValidateAttribute event will not be triggered. 65 */ 66 beforeValidateAttribute: 'beforeValidateAttribute', 67 /** 68 * afterValidateAttribute event is triggered after validating the whole form and each attribute. 69 * The signature of the event handler should be: 70 * function (event, attribute, messages) 71 * where 72 * - event: an Event object. 73 * - attribute: the attribute being validated. Please refer to attributeDefaults for the structure of this parameter. 74 * - messages: an array to which you can add additional validation error messages for the specified attribute. 75 */ 76 afterValidateAttribute: 'afterValidateAttribute', 77 /** 78 * beforeSubmit event is triggered before submitting the form after all validations have passed. 79 * The signature of the event handler should be: 80 * function (event) 81 * where event is an Event object. 82 * 83 * If the handler returns a boolean false, it will stop form submission. 84 */ 85 beforeSubmit: 'beforeSubmit', 86 /** 87 * ajaxBeforeSend event is triggered before sending an AJAX request for AJAX-based validation. 88 * The signature of the event handler should be: 89 * function (event, jqXHR, settings) 90 * where 91 * - event: an Event object. 92 * - jqXHR: a jqXHR object 93 * - settings: the settings for the AJAX request 94 */ 95 ajaxBeforeSend: 'ajaxBeforeSend', 96 /** 97 * ajaxComplete event is triggered after completing an AJAX request for AJAX-based validation. 98 * The signature of the event handler should be: 99 * function (event, jqXHR, textStatus) 100 * where 101 * - event: an Event object. 102 * - jqXHR: a jqXHR object 103 * - textStatus: the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror"). 104 */ 105 ajaxComplete: 'ajaxComplete', 106 /** 107 * afterInit event is triggered after yii activeForm init. 108 * The signature of the event handler should be: 109 * function (event) 110 * where 111 * - event: an Event object. 112 */ 113 afterInit: 'afterInit' 114 }; 115 116 // NOTE: If you change any of these defaults, make sure you update yii\widgets\ActiveForm::getClientOptions() as well 117 var defaults = { 118 // whether to encode the error summary 119 encodeErrorSummary: true, 120 // the jQuery selector for the error summary 121 errorSummary: '.error-summary', 122 // whether to perform validation before submitting the form. 123 validateOnSubmit: true, 124 // the container CSS class representing the corresponding attribute has validation error 125 errorCssClass: 'has-error', 126 // the container CSS class representing the corresponding attribute passes validation 127 successCssClass: 'has-success', 128 // the container CSS class representing the corresponding attribute is being validated 129 validatingCssClass: 'validating', 130 // the GET parameter name indicating an AJAX-based validation 131 ajaxParam: 'ajax', 132 // the type of data that you're expecting back from the server 133 ajaxDataType: 'json', 134 // the URL for performing AJAX-based validation. If not set, it will use the the form's action 135 validationUrl: undefined, 136 // whether to scroll to first visible error after validation. 137 scrollToError: true, 138 // offset in pixels that should be added when scrolling to the first error. 139 scrollToErrorOffset: 0, 140 // where to add validation class: container or input 141 validationStateOn: 'container' 142 }; 143 144 // NOTE: If you change any of these defaults, make sure you update yii\widgets\ActiveField::getClientOptions() as well 145 var attributeDefaults = { 146 // a unique ID identifying an attribute (e.g. "loginform-username") in a form 147 id: undefined, 148 // attribute name or expression (e.g. "[0]content" for tabular input) 149 name: undefined, 150 // the jQuery selector of the container of the input field 151 container: undefined, 152 // the jQuery selector of the input field under the context of the form 153 input: undefined, 154 // the jQuery selector of the error tag under the context of the container 155 error: '.help-block', 156 // whether to encode the error 157 encodeError: true, 158 // whether to perform validation when a change is detected on the input 159 validateOnChange: true, 160 // whether to perform validation when the input loses focus 161 validateOnBlur: true, 162 // whether to perform validation when the user is typing. 163 validateOnType: false, 164 // number of milliseconds that the validation should be delayed when a user is typing in the input field. 165 validationDelay: 500, 166 // whether to enable AJAX-based validation. 167 enableAjaxValidation: false, 168 // function (attribute, value, messages, deferred, $form), the client-side validation function. 169 validate: undefined, 170 // status of the input field, 0: empty, not entered before, 1: validated, 2: pending validation, 3: validating 171 status: 0, 172 // whether the validation is cancelled by beforeValidateAttribute event handler 173 cancelled: false, 174 // the value of the input 175 value: undefined, 176 // whether to update aria-invalid attribute after validation 177 updateAriaInvalid: true 178 }; 179 180 181 var submitDefer; 182 183 var setSubmitFinalizeDefer = function ($form) { 184 submitDefer = $.Deferred(); 185 $form.data('yiiSubmitFinalizePromise', submitDefer.promise()); 186 }; 187 188 // finalize yii.js $form.submit 189 var submitFinalize = function ($form) { 190 if (submitDefer) { 191 submitDefer.resolve(); 192 submitDefer = undefined; 193 $form.removeData('yiiSubmitFinalizePromise'); 194 } 195 }; 196 197 198 var methods = { 199 init: function (attributes, options) { 200 return this.each(function () { 201 var $form = $(this); 202 if ($form.data('yiiActiveForm')) { 203 return; 204 } 205 206 var settings = $.extend({}, defaults, options || {});
207 if (settings.validationUrl === undefined) { 208 settings.validationUrl = $form.attr('action'); 209 } 210 211 $.each(attributes, function (i) { 212 attributes[i] = $.extend({value: getValue($form, this)}, attributeDefaults, this); 213 watchAttribute($form, attributes[i]); 214 }); 215 216 $form.data('yiiActiveForm', { 217 settings: settings, 218 attributes: attributes, 219 submitting: false, 220 validated: false, 221 options: getFormOptions($form) 222 }); 223 224 /** 225 * Clean up error status when the form is reset. 226 * Note that $form.on('reset', ...) does work because the "reset" event does not bubble on IE. 227 */ 228 $form.on('reset.yiiActiveForm', methods.resetForm); 229 230 if (settings.validateOnSubmit) { 231 $form.on('mouseup.yiiActiveForm keyup.yiiActiveForm', ':submit', function () { 232 $form.data('yiiActiveForm').submitObject = $(this); 233 }); 234 $form.on('submit.yiiActiveForm', methods.submitForm); 235 } 236 var event = $.Event(events.afterInit); 237 $form.trigger(event); 238 }); 239 }, 240 241 // add a new attribute to the form dynamically. 242 // please refer to attributeDefaults for the structure of attribute 243 add: function (attribute) { 244 var $form = $(this); 245 attribute = $.extend({value: getValue($form, attribute)}, attributeDefaults, attribute); 246 $form.data('yiiActiveForm').attributes.push(attribute); 247 watchAttribute($form, attribute); 248 }, 249 250 // remove the attribute with the specified ID from the form 251 remove: function (id) { 252 var $form = $(this), 253 attributes = $form.data('yiiActiveForm').attributes, 254 index = -1, 255 attribute = undefined; 256 $.each(attributes, function (i) { 257 if (attributes[i]['id'] == id) { 258 index = i; 259 attribute = attributes[i]; 260 return false; 261 } 262 }); 263 if (index >= 0) { 264 attributes.splice(index, 1); 265 unwatchAttribute($form, attribute); 266 } 267 268 return attribute; 269 }, 270 271 // manually trigger the validation of the attribute with the specified ID 272 validateAttribute: function (id) { 273 var attribute = methods.find.call(this, id); 274 if (attribute != undefined) { 275 validateAttribute($(this), attribute, true); 276 } 277 }, 278 279 // find an attribute config based on the specified attribute ID 280 find: function (id) { 281 var attributes = $(this).data('yiiActiveForm').attributes, 282 result = undefined; 283 $.each(attributes, function (i) { 284 if (attributes[i]['id'] == id) { 285 result = attributes[i]; 286 return false; 287 } 288 }); 289 return result; 290 }, 291 292 destroy: function () { 293 return this.each(function () { 294 $(this).off('.yiiActiveForm'); 295 $(this).removeData('yiiActiveForm'); 296 }); 297 }, 298 299 data: function () { 300 return this.data('yiiActiveForm'); 301 }, 302 303 // validate all applicable inputs in the form 304 validate: function (forceValidate) { 305 if (forceValidate) { 306 $(this).data('yiiActiveForm').submitting = true; 307 } 308 309 var $form = $(this), 310 data = $form.data('yiiActiveForm'), 311 needAjaxValidation = false, 312 messages = {}, 313 deferreds = deferredArray(), 314 submitting = data.submitting; 315 316 if (submitting) { 317 var event = $.Event(events.beforeValidate); 318 $form.trigger(event, [messages, deferreds]); 319 320 if (event.result === false) { 321 data.submitting = false;
322 submitFinalize($form); 323 return; 324 } 325 } 326 327 // client-side validation 328 $.each(data.attributes, function () { 329 this.$form = $form; 330 var $input = findInput($form, this); 331 332 var disabled = $input.toArray().reduce((result, next) => result && $(next).is(':disabled'), true); 333 if (disabled) { 334 return true; 335 } 336 // validate markup for select input 337 if ($input.length && $input[0].tagName.toLowerCase() === 'select') { 338 var opts = $input[0].options, isEmpty = !opts || !opts.length, isRequired = $input.attr('required'), 339 isMultiple = $input.attr('multiple'), size = $input.attr('size') || 1; 340 // check if valid HTML markup for select input, else return validation as `true` 341 // https://w3c.github.io/html-reference/select.html 342 if (isRequired && !isMultiple && parseInt(size, 10) === 1) { // invalid select markup condition 343 if (isEmpty) { // empty option elements for the select 344 return true; 345 } 346 if (opts[0] && (opts[0].value !== '' && opts[0].text !== '')) { // first option is not empty 347 return true; 348 } 349 } 350 } 351 this.cancelled = false; 352 // perform validation only if the form is being submitted or if an attribute is pending validation 353 if (data.submitting || this.status === 2 || this.status === 3) { 354 var msg = messages[this.id]; 355 if (msg === undefined) { 356 msg = []; 357 messages[this.id] = msg; 358 } 359 360 var event = $.Event(events.beforeValidateAttribute); 361 $form.trigger(event, [this, msg, deferreds]); 362 if (event.result !== false) { 363 if (this.validate) { 364 this.validate(this, getValue($form, this), msg, deferreds, $form); 365 } 366 if (this.enableAjaxValidation) { 367 needAjaxValidation = true; 368 } 369 } else { 370 this.cancelled = true; 371 } 372 } 373 }); 374 375 // ajax validation 376 $.when.apply(this, deferreds).always(function () { 377 // Remove empty message arrays 378 for (var i in messages) { 379 if (0 === messages[i].length) { 380 delete messages[i]; 381 } 382 } 383 if (needAjaxValidation && ($.isEmptyObject(messages) || data.submitting)) { 384 var $button = data.submitObject, 385 extData = '&' + data.settings.ajaxParam + '=' + $form.attr('id'); 386 if ($button && $button.length && $button.attr('name')) { 387 extData += '&' + $button.attr('name') + '=' + $button.attr('value'); 388 } 389 $.ajax({ 390 url: data.settings.validationUrl, 391 type: $form.attr('method'), 392 data: $form.serialize() + extData, 393 dataType: data.settings.ajaxDataType, 394 complete: function (jqXHR, textStatus) { 395 $form.trigger(events.ajaxComplete, [jqXHR, textStatus]); 396 }, 397 beforeSend: function (jqXHR, settings) { 398 $form.trigger(events.ajaxBeforeSend, [jqXHR, settings]); 399 }, 400 success: function (msgs) { 401 if (msgs !== null && typeof msgs === 'object') { 402 $.each(data.attributes, function () { 403 if (!this.enableAjaxValidation || this.cancelled) { 404 delete msgs[this.id]; 405 } 406 }); 407 updateInputs($form, $.extend(messages, msgs), submitting); 408 } else { 409 updateInputs($form, messages, submitting); 410 } 411 }, 412 error: function () { 413 data.submitting = false;
414 submitFinalize($form); 415 } 416 }); 417 } else { 418 if (data.submitting) { 419 // delay callback so that the form can be submitted without problem 420 window.setTimeout(function () { 421 updateInputs($form, messages, submitting); 422 }, 200); 423 } else { 424 updateInputs($form, messages, submitting); 425 } 426 } 427 }); 428 }, 429 430 submitForm: function () { 431 var $form = $(this), 432 data = $form.data('yiiActiveForm'); 433 if (data.validated) { 434 // Second submit's call (from validate/updateInputs) 435 data.submitting = false; 436 var event = $.Event(events.beforeSubmit); 437 $form.trigger(event); 438 if (event.result === false) { 439 data.validated = false; 440 submitFinalize($form); 441 return false; 442 } 443 updateHiddenButton($form); 444 return true; // continue submitting the form since validation passes 445 } else { 446 // First submit's call (from yii.js/handleAction) - execute validating 447 setSubmitFinalizeDefer($form); 448 449 if (data.settings.timer !== undefined) { 450 clearTimeout(data.settings.timer); 451 } 452 data.submitting = true; 453 methods.validate.call($form); 454 return false; 455 } 456 }, 457 458 resetForm: function () { 459 var $form = $(this); 460 var data = $form.data('yiiActiveForm'); 461 // Because we bind directly to a form reset event instead of a reset button (that may not exist), 462 // when this function is executed form input values have not been reset yet. 463 // Therefore we do the actual reset work through setTimeout. 464 window.setTimeout(function () { 465 $.each(data.attributes, function () {
466 // Without setTimeout() we would get the input values that are not reset yet. 467 this.value = getValue($form, this); 468 this.status = 0; 469 var $container = $form.find(this.container), 470 $input = findInput($form, this), 471 $errorElement = data.settings.validationStateOn === 'input' ? $input : $container; 472 473 $errorElement.removeClass( 474 data.settings.validatingCssClass + ' ' + 475 data.settings.errorCssClass + ' ' + 476 data.settings.successCssClass 477 ); 478 $container.find(this.error).html(''); 479 }); 480 $form.find(data.settings.errorSummary).hide().find('ul').html(''); 481 }, 1); 482 }, 483 484 /** 485 * Updates error messages, input containers, and optionally summary as well. 486 * If an attribute is missing from messages, it is considered valid. 487 * @param messages array the validation error messages, indexed by attribute IDs 488 * @param summary whether to update summary as well. 489 */ 490 updateMessages: function (messages, summary) { 491 var $form = $(this); 492 var data = $form.data('yiiActiveForm'); 493 $.each(data.attributes, function () { 494 updateInput($form, this, messages); 495 }); 496 if (summary) { 497 updateSummary($form, messages); 498 } 499 }, 500 501 /** 502 * Updates error messages and input container of a single attribute. 503 * If messages is empty, the attribute is considered valid. 504 * @param id attribute ID 505 * @param messages array with error messages 506 */ 507 updateAttribute: function (id, messages) { 508 var attribute = methods.find.call(this, id); 509 if (attribute != undefined) { 510 var msg = {}; 511 msg[id] = messages; 512 updateInput($(this), attribute, msg); 513 } 514 } 515 }; 516 517 var watchAttribute = function ($form, attribute) { 518 var $input = findInput($form, attribute); 519 if (attribute.validateOnChange) { 520 $input.on('change.yiiActiveForm', function () { 521 validateAttribute($form, attribute, false); 522 }); 523 } 524 if (attribute.validateOnBlur) { 525 $input.on('blur.yiiActiveForm', function () { 526 if (attribute.status == 0 || attribute.status == 1) { 527 validateAttribute($form, attribute, true); 528 } 529 }); 530 } 531 if (attribute.validateOnType) { 532 $input.on('keyup.yiiActiveForm', function (e) { 533 if ($.inArray(e.which, [16, 17, 18, 37, 38, 39, 40]) !== -1) { 534 return; 535 } 536 if (attribute.value !== getValue($form, attribute)) { 537 validateAttribute($form, attribute, false, attribute.validationDelay); 538 } 539 }); 540 } 541 }; 542 543 var unwatchAttribute = function ($form, attribute) { 544 findInput($form, attribute).off('.yiiActiveForm'); 545 }; 546 547 var validateAttribute = function ($form, attribute, forceValidate, validationDelay) { 548 var data = $form.data('yiiActiveForm'); 549 550 if (forceValidate) { 551 attribute.status = 2; 552 } 553 $.each(data.attributes, function () { 554 if (!isEqual(this.value, getValue($form, this))) { 555 this.status = 2; 556 forceValidate = true; 557 } 558 }); 559 if (!forceValidate) { 560 return; 561 } 562 563 if (data.settings.timer !== undefined) { 564 clearTimeout(data.settings.timer); 565 } 566 data.settings.timer = window.setTimeout(function () { 567 if (data.submitting || $form.is(':hidden')) { 568 return; 569 } 570 $.each(data.attributes, function () { 571 if (this.status === 2) { 572 this.status = 3; 573 574 var $container = $form.find(this.container), 575 $input = findInput($form, this); 576
577 var $errorElement = data.settings.validationStateOn === 'input' ? $input : $container; 578 579 $errorElement.addClass(data.settings.validatingCssClass); 580 } 581 }); 582 methods.validate.call($form); 583 }, validationDelay ? validationDelay : 200); 584 }; 585 586 /** 587 * Compares two value whatever it objects, arrays or simple types 588 * @param val1 589 * @param val2 590 * @returns boolean 591 */ 592 var isEqual = function (val1, val2) { 593 // objects 594 if (val1 instanceof Object) { 595 return isObjectsEqual(val1, val2) 596 } 597 598 // arrays 599 if (Array.isArray(val1)) { 600 return isArraysEqual(val1, val2); 601 } 602 603 // simple types 604 return val1 === val2; 605 }; 606 607 /** 608 * Compares two objects 609 * @param obj1 610 * @param obj2 611 * @returns boolean 612 */ 613 var isObjectsEqual = function (obj1, obj2) { 614 if (!(obj1 instanceof Object) || !(obj2 instanceof Object)) { 615 return false; 616 } 617 618 var keys1 = Object.keys(obj1); 619 var keys2 = Object.keys(obj2); 620 if (keys1.length !== keys2.length) { 621 return false; 622 } 623 624 for (var i = 0; i < keys1.length; i += 1) { 625 if (!obj2.hasOwnProperty(keys1[i])) { 626 return false; 627 } 628 if (obj1[keys1[i]] !== obj2[keys1[i]]) { 629 return false; 630 } 631 } 632 633 return true; 634 }; 635 636 /** 637 * Compares two arrays 638 * @param arr1 639 * @param arr2 640 * @returns boolean 641 */ 642 var isArraysEqual = function (arr1, arr2) { 643 if (!Array.isArray(arr1) || !Array.isArray(arr2)) { 644 return false; 645 } 646 647 if (arr1.length !== arr2.length) { 648 return false; 649 } 650 for (var i = 0; i < arr1.length; i += 1) { 651 if (arr1[i] !== arr2[i]) { 652 return false; 653 } 654 } 655 return true; 656 }; 657 658 /** 659 * Returns an array prototype with a shortcut method for adding a new deferred. 660 * The context of the callback will be the deferred object so it can be resolved like ```this.resolve()``` 661 * @returns Array 662 */ 663 var deferredArray = function () { 664 var array = []; 665 array.add = function (callback) { 666 this.push(new $.Deferred(callback)); 667 }; 668 return array; 669 }; 670 671 var buttonOptions = ['action', 'target', 'method', 'enctype']; 672 673 /** 674 * Returns current form options 675 * @param $form 676 * @returns object Object with button of form options 677 */ 678 var getFormOptions = function ($form) { 679 var attributes = {}; 680 for (var i = 0; i < buttonOptions.length; i++) { 681 attributes[buttonOptions[i]] = $form.attr(buttonOptions[i]); 682 } 683 684 return attributes; 685 }; 686 687 /** 688 * Applies temporary form options related to submit button 689 * @param $form the form jQuery object 690 * @param $button the button jQuery object 691 */ 692 var applyButtonOptions = function ($form, $button) { 693 for (var i = 0; i < buttonOptions.length; i++) { 694 var value = $button.attr('form' + buttonOptions[i]); 695 if (value) { 696 $form.attr(buttonOptions[i], value); 697 } 698 } 699 }; 700 701 /** 702 * Restores original form options 703 * @param $form the form jQuery object 704 */ 705 var restoreButtonOptions = function ($form) { 706 var data = $form.data('yiiActiveForm'); 707 708 for (var i = 0; i < buttonOptions.length; i++) { 709 $form.attr(buttonOptions[i], data.options[buttonOptions[i]] || null); 710 } 711 }; 712 713 /** 714 * Updates the error messages and the input containers for all applicable attributes 715 * @param $form the form jQuery object 716 * @param messages array the validation error messages 717 * @param submitting whether this method is called after validation triggered by form submission 718 */ 719 var updateInputs = function ($form, messages, submitting) { 720 var data = $form.data('yiiActiveForm'); 721 722 if (data === undefined) { 723 return false;
724 } 725 726 var errorAttributes = [], $input; 727 $.each(data.attributes, function () { 728 var hasError = (submitting && updateInput($form, this, messages)) || (!submitting && attrHasError($form, 729 this, messages)); 730 $input = findInput($form, this); 731 732 if (!$input.is(':disabled') && !this.cancelled && hasError) { 733 errorAttributes.push(this); 734 } 735 }); 736 737 $form.trigger(events.afterValidate, [messages, errorAttributes]); 738 739 if (submitting) { 740 updateSummary($form, messages); 741 if (errorAttributes.length) { 742 if (data.settings.scrollToError) { 743 var h = $(document).height(), top = $form.find($.map(errorAttributes, function (attribute) { 744 return attribute.input; 745 }).join(',')).first().closest(':visible').offset().top - data.settings.scrollToErrorOffset; 746 top = top < 0 ? 0 : (top > h ? h : top); 747 var wtop = $(window).scrollTop(); 748 if (top < wtop || top > wtop + $(window).height()) { 749 $(window).scrollTop(top); 750 } 751 } 752 data.submitting = false; 753 } else { 754 data.validated = true; 755 if (data.submitObject) { 756 applyButtonOptions($form, data.submitObject); 757 } 758 $form.submit(); 759 if (data.submitObject) { 760 restoreButtonOptions($form); 761 } 762 } 763 } else { 764 $.each(data.attributes, function () { 765 if (!this.cancelled && (this.status === 2 || this.status === 3)) { 766 updateInput($form, this, messages); 767 } 768 }); 769 } 770 submitFinalize($form); 771 }; 772 773 /** 774 * Updates hidden field that represents clicked submit button. 775 * @param $form the form jQuery object. 776 */ 777 var updateHiddenButton = function ($form) { 778 var data = $form.data('yiiActiveForm'); 779 var $button = data.submitObject || $form.find(':submit:first'); 780 // TODO: if the submission is caused by "change" event, it will not work 781 if ($button.length && $button.attr('type') == 'submit' && $button.attr('name')) { 782 // simulate button input value 783 var $hiddenButton = $('input[type="hidden"][name="' + $button.attr('name') + '"]', $form); 784 if (!$hiddenButton.length) { 785 $('<input>').attr({ 786 type: 'hidden', 787 name: $button.attr('name'), 788 value: $button.attr('value') 789 }).appendTo($form); 790 } else { 791 $hiddenButton.attr('value', $button.attr('value')); 792 } 793 } 794 }; 795 796 /** 797 * Updates the error message and the input container for a particular attribute. 798 * @param $form the form jQuery object 799 * @param attribute object the configuration for a particular attribute. 800 * @param messages array the validation error messages 801 * @return boolean whether there is a validation error for the specified attribute 802 */ 803 var updateInput = function ($form, attribute, messages) { 804 var data = $form.data('yiiActiveForm'), 805 $input = findInput($form, attribute), 806 hasError = attrHasError($form, attribute, messages); 807 808 if (!$.isArray(messages[attribute.id])) { 809 messages[attribute.id] = []; 810 } 811 812 attribute.status = 1; 813 if ($input.length) { 814 var $container = $form.find(attribute.container); 815 var $error = $container.find(attribute.error); 816 updateAriaInvalid($form, attribute, hasError); 817 818 var $errorElement = data.settings.validationStateOn === 'input' ? $input : $container; 819 820 if (hasError) { 821 if (attribute.encodeError) { 822 $error.text(messages[attribute.id][0]); 823 } else { 824 $error.html(messages[attribute.id][0]); 825 }
826 $errorElement.removeClass(data.settings.validatingCssClass + ' ' + data.settings.successCssClass) 827 .addClass(data.settings.errorCssClass); 828 } else { 829 $error.empty(); 830 $errorElement.removeClass(data.settings.validatingCssClass + ' ' + data.settings.errorCssClass + ' ') 831 .addClass(data.settings.successCssClass); 832 } 833 attribute.value = getValue($form, attribute); 834 } 835 836 $form.trigger(events.afterValidateAttribute, [attribute, messages[attribute.id]]); 837 838 return hasError; 839 }; 840 841 /** 842 * Checks if a particular attribute has an error 843 * @param $form the form jQuery object 844 * @param attribute object the configuration for a particular attribute. 845 * @param messages array the validation error messages 846 * @return boolean whether there is a validation error for the specified attribute 847 */ 848 var attrHasError = function ($form, attribute, messages) { 849 var $input = findInput($form, attribute), 850 hasError = false; 851 852 if (!$.isArray(messages[attribute.id])) { 853 messages[attribute.id] = []; 854 } 855 856 if ($input.length) { 857 hasError = messages[attribute.id].length > 0; 858 } 859 860 return hasError; 861 }; 862 863 /** 864 * Updates the error summary. 865 * @param $form the form jQuery object 866 * @param messages array the validation error messages 867 */ 868 var updateSummary = function ($form, messages) { 869 var data = $form.data('yiiActiveForm'), 870 $summary = $form.find(data.settings.errorSummary), 871 $ul = $summary.find('ul').empty(); 872 873 if ($summary.length && messages) { 874 $.each(data.attributes, function () { 875 if ($.isArray(messages[this.id]) && messages[this.id].length) { 876 var error = $('<li/>'); 877 if (data.settings.encodeErrorSummary) { 878 error.text(messages[this.id][0]); 879 } else { 880 error.html(messages[this.id][0]); 881 } 882 $ul.append(error); 883 } 884 }); 885 $summary.toggle($ul.find('li').length > 0); 886 } 887 }; 888 889 var getValue = function ($form, attribute) { 890 var $input = findInput($form, attribute); 891 var type = $input.attr('type'); 892 if (type === 'checkbox' || type === 'radio') { 893 var $realInput = $input.filter(':checked'); 894 if ($realInput.length > 1) { 895 var values = []; 896 $realInput.each(function (index) { 897 values.push($($realInput.get(index)).val()); 898 }); 899 return values; 900 } 901 902 if (!$realInput.length) { 903 $realInput = $form.find('input[type=hidden][name="' + $input.attr('name') + '"]'); 904 } 905 906 return $realInput.val(); 907 } else { 908 return $input.val(); 909 } 910 }; 911 912 var findInput = function ($form, attribute) { 913 var $input = $form.find(attribute.input); 914 if ($input.length && $input[0].tagName.toLowerCase() === 'div') { 915 // checkbox list or radio list 916 return $input.find('input'); 917 } else { 918 return $input; 919 } 920 }; 921 922 var updateAriaInvalid = function ($form, attribute, hasError) { 923 if (attribute.updateAriaInvalid) { 924 $form.find(attribute.input).attr('aria-invalid', hasError ? 'true' : 'false'); 925 } 926 } 927})(window.jQuery);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.