1/** 2 * Yii form widget. 3 * 4 * This is the JavaScript widget used by the yii\widgets\ActiveForm widget. 5 * 6 * @link https://www.yiiframework.com/ 7 * @copyright Copyright (c) 2008 Yii Software LLC 8 * @license https://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 validate_only: false, // validate without auto submitting 222 options: getFormOptions($form) 223 }); 224 225 /** 226 * Clean up error status when the form is reset. 227 * Note that $form.on('reset', ...) does work because the "reset" event does not bubble on IE. 228 */ 229 $form.on('reset.yiiActiveForm', methods.resetForm); 230 231 if (settings.validateOnSubmit) { 232 $form.on('mouseup.yiiActiveForm keyup.yiiActiveForm', ':submit', function () { 233 $form.data('yiiActiveForm').submitObject = $(this); 234 }); 235 $form.on('submit.yiiActiveForm', methods.submitForm); 236 } 237 var event = $.Event(events.afterInit); 238 $form.trigger(event); 239 }); 240 }, 241 242 // add a new attribute to the form dynamically. 243 // please refer to attributeDefaults for the structure of attribute 244 add: function (attribute) { 245 var $form = $(this); 246 attribute = $.extend({value: getValue($form, attribute)}, attributeDefaults, attribute); 247 $form.data('yiiActiveForm').attributes.push(attribute); 248 watchAttribute($form, attribute); 249 }, 250 251 // remove the attribute with the specified ID from the form 252 remove: function (id) { 253 var $form = $(this), 254 attributes = $form.data('yiiActiveForm').attributes, 255 index = -1, 256 attribute = undefined; 257 $.each(attributes, function (i) { 258 if (attributes[i]['id'] == id) { 259 index = i; 260 attribute = attributes[i]; 261 return false; 262 } 263 }); 264 if (index >= 0) { 265 attributes.splice(index, 1); 266 unwatchAttribute($form, attribute); 267 } 268 269 return attribute; 270 }, 271 272 // manually trigger the validation of the attribute with the specified ID 273 validateAttribute: function (id) { 274 var attribute = methods.find.call(this, id); 275 if (attribute != undefined) { 276 validateAttribute($(this), attribute, true); 277 } 278 }, 279 280 // find an attribute config based on the specified attribute ID 281 find: function (id) { 282 var attributes = $(this).data('yiiActiveForm').attributes, 283 result = undefined; 284 $.each(attributes, function (i) { 285 if (attributes[i]['id'] == id) { 286 result = attributes[i]; 287 return false; 288 } 289 }); 290 return result; 291 }, 292 293 destroy: function () { 294 return this.each(function () { 295 $(this).off('.yiiActiveForm'); 296 $(this).removeData('yiiActiveForm'); 297 }); 298 }, 299 300 data: function () { 301 return this.data('yiiActiveForm'); 302 }, 303 304 // validate all applicable inputs in the form 305 validate: function (forceValidate) { 306 if (forceValidate) { 307 $(this).data('yiiActiveForm').submitting = true; 308 } 309 310 var $form = $(this), 311 data = $form.data('yiiActiveForm'), 312 needAjaxValidation = false, 313 messages = {}, 314 deferreds = deferredArray(), 315 submitting = data.submitting; 316 317 if (submitting) { 318 var event = $.Event(events.beforeValidate); 319 $form.trigger(event, [messages, deferreds]); 320 321 if (event.result === false) { 322 data.submitting = false;
323 submitFinalize($form); 324 return; 325 } 326 } 327 328 // client-side validation 329 $.each(data.attributes, function () { 330 this.$form = $form; 331 var $input = findInput($form, this); 332 333 var disabled = $input.toArray().reduce(function(result, next) { 334 return result && $(next).is(':disabled'); 335 }, true); 336 if (disabled) { 337 return true; 338 } 339 // validate markup for select input 340 if ($input.length && $input[0].tagName.toLowerCase() === 'select') { 341 var opts = $input[0].options, isEmpty = !opts || !opts.length, isRequired = $input.attr('required'), 342 isMultiple = $input.attr('multiple'), size = $input.attr('size') || 1; 343 // check if valid HTML markup for select input, else return validation as `true` 344 // https://w3c.github.io/html-reference/select.html 345 if (isRequired && !isMultiple && parseInt(size, 10) === 1) { // invalid select markup condition 346 if (isEmpty) { // empty option elements for the select 347 return true; 348 } 349 if (opts[0] && (opts[0].value !== '' && opts[0].text !== '')) { // first option is not empty 350 return true; 351 } 352 } 353 } 354 this.cancelled = false; 355 // perform validation only if the form is being submitted or if an attribute is pending validation 356 if (data.submitting || this.status === 2 || this.status === 3) { 357 var msg = messages[this.id]; 358 if (msg === undefined) { 359 msg = []; 360 messages[this.id] = msg; 361 } 362 363 var event = $.Event(events.beforeValidateAttribute); 364 $form.trigger(event, [this, msg, deferreds]); 365 if (event.result !== false) { 366 if (this.validate) { 367 this.validate(this, getValue($form, this), msg, deferreds, $form); 368 } 369 if (this.enableAjaxValidation) { 370 needAjaxValidation = true; 371 } 372 } else { 373 this.cancelled = true; 374 } 375 } 376 }); 377 378 // ajax validation 379 $.when.apply(this, deferreds).always(function () { 380 // Remove empty message arrays 381 for (var i in messages) { 382 if (0 === messages[i].length) { 383 delete messages[i]; 384 } 385 } 386 if (needAjaxValidation && ($.isEmptyObject(messages) || data.submitting)) { 387 var $button = data.submitObject, 388 extData = '&' + data.settings.ajaxParam + '=' + $form.attr('id'); 389 if ($button && $button.length && $button.attr('name')) { 390 extData += '&' + $button.attr('name') + '=' + $button.attr('value'); 391 } 392 $.ajax({ 393 url: data.settings.validationUrl, 394 type: $form.attr('method'), 395 data: $form.serialize() + extData, 396 dataType: data.settings.ajaxDataType, 397 complete: function (jqXHR, textStatus) { 398 $form.trigger(events.ajaxComplete, [jqXHR, textStatus]); 399 }, 400 beforeSend: function (jqXHR, settings) { 401 $form.trigger(events.ajaxBeforeSend, [jqXHR, settings]); 402 }, 403 success: function (msgs) { 404 if (msgs !== null && typeof msgs === 'object') { 405 $.each(data.attributes, function () { 406 if (!this.enableAjaxValidation || this.cancelled) { 407 delete msgs[this.id]; 408 } 409 }); 410 updateInputs($form, $.extend(messages, msgs), submitting); 411 } else { 412 updateInputs($form, messages, submitting); 413 } 414 }, 415 error: function () { 416 data.submitting = false;
417 submitFinalize($form); 418 } 419 }); 420 } else { 421 if (data.submitting) { 422 // delay callback so that the form can be submitted without problem 423 window.setTimeout(function () { 424 updateInputs($form, messages, submitting); 425 }, 200); 426 } else { 427 updateInputs($form, messages, submitting); 428 } 429 } 430 }); 431 }, 432 433 submitForm: function () { 434 var $form = $(this), 435 data = $form.data('yiiActiveForm'); 436 if (data.validated) { 437 // Second submit's call (from validate/updateInputs) 438 data.submitting = false; 439 var event = $.Event(events.beforeSubmit); 440 $form.trigger(event); 441 if (event.result === false) { 442 data.validated = false; 443 submitFinalize($form); 444 return false; 445 } 446 updateHiddenButton($form); 447 return true; // continue submitting the form since validation passes 448 } else { 449 // First submit's call (from yii.js/handleAction) - execute validating 450 setSubmitFinalizeDefer($form); 451 452 if (data.settings.timer !== undefined) { 453 clearTimeout(data.settings.timer); 454 } 455 data.submitting = true; 456 methods.validate.call($form); 457 return false; 458 } 459 }, 460 461 resetForm: function () { 462 var $form = $(this); 463 var data = $form.data('yiiActiveForm'); 464 // Because we bind directly to a form reset event instead of a reset button (that may not exist), 465 // when this function is executed form input values have not been reset yet. 466 // Therefore we do the actual reset work through setTimeout. 467 window.setTimeout(function () { 468 $.each(data.attributes, function () {
469 // Without setTimeout() we would get the input values that are not reset yet. 470 this.value = getValue($form, this); 471 this.status = 0; 472 var $container = $form.find(this.container), 473 $input = findInput($form, this), 474 $errorElement = data.settings.validationStateOn === 'input' ? $input : $container; 475 476 $errorElement.removeClass( 477 data.settings.validatingCssClass + ' ' + 478 data.settings.errorCssClass + ' ' + 479 data.settings.successCssClass 480 ); 481 $container.find(this.error).html(''); 482 }); 483 $form.find(data.settings.errorSummary).hide().find('ul').html(''); 484 }, 1); 485 }, 486 487 /** 488 * Updates error messages, input containers, and optionally summary as well. 489 * If an attribute is missing from messages, it is considered valid. 490 * @param messages array the validation error messages, indexed by attribute IDs 491 * @param summary whether to update summary as well. 492 */ 493 updateMessages: function (messages, summary) { 494 var $form = $(this); 495 var data = $form.data('yiiActiveForm'); 496 $.each(data.attributes, function () { 497 updateInput($form, this, messages); 498 }); 499 if (summary) { 500 updateSummary($form, messages); 501 } 502 }, 503 504 /** 505 * Updates error messages and input container of a single attribute. 506 * If messages is empty, the attribute is considered valid. 507 * @param id attribute ID 508 * @param messages array with error messages 509 */ 510 updateAttribute: function (id, messages) { 511 var attribute = methods.find.call(this, id); 512 if (attribute != undefined) { 513 var msg = {}; 514 msg[id] = messages; 515 updateInput($(this), attribute, msg); 516 } 517 } 518 }; 519 520 var watchAttribute = function ($form, attribute) { 521 var $input = findInput($form, attribute); 522 if (attribute.validateOnChange) { 523 $input.on('change.yiiActiveForm', function () { 524 validateAttribute($form, attribute, false); 525 }); 526 } 527 if (attribute.validateOnBlur) { 528 $input.on('blur.yiiActiveForm', function () { 529 if (attribute.status == 0 || attribute.status == 1) { 530 validateAttribute($form, attribute, true); 531 } 532 }); 533 } 534 if (attribute.validateOnType) { 535 $input.on('keyup.yiiActiveForm', function (e) { 536 if ($.inArray(e.which, [16, 17, 18, 37, 38, 39, 40]) !== -1) { 537 return; 538 } 539 if (attribute.value !== getValue($form, attribute)) { 540 validateAttribute($form, attribute, false, attribute.validationDelay); 541 } 542 }); 543 } 544 }; 545 546 var unwatchAttribute = function ($form, attribute) { 547 findInput($form, attribute).off('.yiiActiveForm'); 548 }; 549 550 var validateAttribute = function ($form, attribute, forceValidate, validationDelay) { 551 var data = $form.data('yiiActiveForm'); 552 553 if (forceValidate) { 554 attribute.status = 2; 555 } 556 $.each(data.attributes, function () { 557 if (!isEqual(this.value, getValue($form, this))) { 558 this.status = 2; 559 forceValidate = true; 560 } 561 }); 562 if (!forceValidate) { 563 return; 564 } 565 566 if (data.settings.timer !== undefined) { 567 clearTimeout(data.settings.timer); 568 } 569 data.settings.timer = window.setTimeout(function () { 570 if (data.submitting || $form.is(':hidden')) { 571 return; 572 } 573 $.each(data.attributes, function () { 574 if (this.status === 2) { 575 this.status = 3; 576 577 var $container = $form.find(this.container), 578 $input = findInput($form, this); 579
580 var $errorElement = data.settings.validationStateOn === 'input' ? $input : $container; 581 582 $errorElement.addClass(data.settings.validatingCssClass); 583 } 584 }); 585 methods.validate.call($form); 586 }, validationDelay ? validationDelay : 200); 587 }; 588 589 /** 590 * Compares two value whatever it objects, arrays or simple types 591 * @param val1 592 * @param val2 593 * @returns boolean 594 */ 595 var isEqual = function (val1, val2) { 596 // objects 597 if (val1 instanceof Object) { 598 return isObjectsEqual(val1, val2) 599 } 600 601 // arrays 602 if (Array.isArray(val1)) { 603 return isArraysEqual(val1, val2); 604 } 605 606 // simple types 607 return val1 === val2; 608 }; 609 610 /** 611 * Compares two objects 612 * @param obj1 613 * @param obj2 614 * @returns boolean 615 */ 616 var isObjectsEqual = function (obj1, obj2) { 617 if (!(obj1 instanceof Object) || !(obj2 instanceof Object)) { 618 return false; 619 } 620 621 var keys1 = Object.keys(obj1); 622 var keys2 = Object.keys(obj2); 623 if (keys1.length !== keys2.length) { 624 return false; 625 } 626 627 for (var i = 0; i < keys1.length; i += 1) { 628 if (!obj2.hasOwnProperty(keys1[i])) { 629 return false; 630 } 631 if (obj1[keys1[i]] !== obj2[keys1[i]]) { 632 return false; 633 } 634 } 635 636 return true; 637 }; 638 639 /** 640 * Compares two arrays 641 * @param arr1 642 * @param arr2 643 * @returns boolean 644 */ 645 var isArraysEqual = function (arr1, arr2) { 646 if (!Array.isArray(arr1) || !Array.isArray(arr2)) { 647 return false; 648 } 649 650 if (arr1.length !== arr2.length) { 651 return false; 652 } 653 for (var i = 0; i < arr1.length; i += 1) { 654 if (arr1[i] !== arr2[i]) { 655 return false; 656 } 657 } 658 return true; 659 }; 660 661 /** 662 * Returns an array prototype with a shortcut method for adding a new deferred. 663 * The context of the callback will be the deferred object so it can be resolved like ```this.resolve()``` 664 * @returns Array 665 */ 666 var deferredArray = function () { 667 var array = []; 668 array.add = function (callback) { 669 this.push(new $.Deferred(callback)); 670 }; 671 return array; 672 }; 673 674 var buttonOptions = ['action', 'target', 'method', 'enctype']; 675 676 /** 677 * Returns current form options 678 * @param $form 679 * @returns object Object with button of form options 680 */ 681 var getFormOptions = function ($form) { 682 var attributes = {}; 683 for (var i = 0; i < buttonOptions.length; i++) { 684 attributes[buttonOptions[i]] = $form.attr(buttonOptions[i]); 685 } 686 687 return attributes; 688 }; 689 690 /** 691 * Applies temporary form options related to submit button 692 * @param $form the form jQuery object 693 * @param $button the button jQuery object 694 */ 695 var applyButtonOptions = function ($form, $button) { 696 for (var i = 0; i < buttonOptions.length; i++) { 697 var value = $button.attr('form' + buttonOptions[i]); 698 if (value) { 699 $form.attr(buttonOptions[i], value); 700 } 701 } 702 }; 703 704 /** 705 * Restores original form options 706 * @param $form the form jQuery object 707 */ 708 var restoreButtonOptions = function ($form) { 709 var data = $form.data('yiiActiveForm'); 710 711 for (var i = 0; i < buttonOptions.length; i++) { 712 $form.attr(buttonOptions[i], data.options[buttonOptions[i]] || null); 713 } 714 }; 715 716 /** 717 * Updates the error messages and the input containers for all applicable attributes 718 * @param $form the form jQuery object 719 * @param messages array the validation error messages 720 * @param submitting whether this method is called after validation triggered by form submission 721 */ 722 var updateInputs = function ($form, messages, submitting) { 723 var data = $form.data('yiiActiveForm'); 724 725 if (data === undefined) { 726 return false;
727 } 728 729 var errorAttributes = [], $input; 730 $.each(data.attributes, function () { 731 var hasError = (submitting && updateInput($form, this, messages)) || (!submitting && attrHasError($form, 732 this, messages)); 733 $input = findInput($form, this); 734 735 if (!$input.is(':disabled') && !this.cancelled && hasError) { 736 errorAttributes.push(this); 737 } 738 }); 739 740 $form.trigger(events.afterValidate, [messages, errorAttributes]); 741 742 if (submitting) { 743 updateSummary($form, messages); 744 if (errorAttributes.length) { 745 if (data.settings.scrollToError) { 746 var h = $(document).height(), top = $form.find($.map(errorAttributes, function (attribute) { 747 return attribute.input; 748 }).join(',')).first().closest(':visible').offset().top - data.settings.scrollToErrorOffset; 749 top = top < 0 ? 0 : (top > h ? h : top); 750 var wtop = $(window).scrollTop(); 751 if (top < wtop || top > wtop + $(window).height()) { 752 $(window).scrollTop(top); 753 } 754 } 755 data.submitting = false; 756 } else { 757 data.validated = true; 758 if (!data.validate_only) { 759 if (data.submitObject) { 760 applyButtonOptions($form, data.submitObject); 761 } 762 $form.submit(); 763 if (data.submitObject) { 764 restoreButtonOptions($form); 765 } 766 } 767 } 768 } else { 769 $.each(data.attributes, function () { 770 if (!this.cancelled && (this.status === 2 || this.status === 3)) { 771 updateInput($form, this, messages); 772 } 773 }); 774 } 775 submitFinalize($form); 776 }; 777 778 /** 779 * Updates hidden field that represents clicked submit button. 780 * @param $form the form jQuery object. 781 */ 782 var updateHiddenButton = function ($form) { 783 var data = $form.data('yiiActiveForm'); 784 var $button = data.submitObject || $form.find(':submit:first'); 785 // TODO: if the submission is caused by "change" event, it will not work 786 if ($button.length && $button.attr('type') == 'submit' && $button.attr('name')) { 787 // simulate button input value 788 var $hiddenButton = $('input[type="hidden"][name="' + $button.attr('name') + '"]', $form); 789 if (!$hiddenButton.length) { 790 $('<input>').attr({ 791 type: 'hidden', 792 name: $button.attr('name'), 793 value: $button.attr('value') 794 }).appendTo($form); 795 } else { 796 $hiddenButton.attr('value', $button.attr('value')); 797 } 798 } 799 }; 800 801 /** 802 * Updates the error message and the input container for a particular attribute. 803 * @param $form the form jQuery object 804 * @param attribute object the configuration for a particular attribute. 805 * @param messages array the validation error messages 806 * @return boolean whether there is a validation error for the specified attribute 807 */ 808 var updateInput = function ($form, attribute, messages) { 809 var data = $form.data('yiiActiveForm'), 810 $input = findInput($form, attribute), 811 hasError = attrHasError($form, attribute, messages); 812 813 if (!$.isArray(messages[attribute.id])) { 814 messages[attribute.id] = []; 815 } 816 817 attribute.status = 1; 818 if ($input.length) { 819 var $container = $form.find(attribute.container); 820 var $error = $container.find(attribute.error); 821 updateAriaInvalid($form, attribute, hasError); 822 823 var $errorElement = data.settings.validationStateOn === 'input' ? $input : $container; 824 825 if (hasError) { 826 if (attribute.encodeError) { 827 $error.text(messages[attribute.id][0]); 828 } else { 829 $error.html(messages[attribute.id][0]); 830 }
831 $errorElement.removeClass(data.settings.validatingCssClass + ' ' + data.settings.successCssClass) 832 .addClass(data.settings.errorCssClass); 833 } else { 834 $error.empty(); 835 $errorElement.removeClass(data.settings.validatingCssClass + ' ' + data.settings.errorCssClass + ' ') 836 .addClass(data.settings.successCssClass); 837 } 838 attribute.value = getValue($form, attribute); 839 } 840 841 $form.trigger(events.afterValidateAttribute, [attribute, messages[attribute.id]]); 842 843 return hasError; 844 }; 845 846 /** 847 * Checks if a particular attribute has an error 848 * @param $form the form jQuery object 849 * @param attribute object the configuration for a particular attribute. 850 * @param messages array the validation error messages 851 * @return boolean whether there is a validation error for the specified attribute 852 */ 853 var attrHasError = function ($form, attribute, messages) { 854 var $input = findInput($form, attribute), 855 hasError = false; 856 857 if (!$.isArray(messages[attribute.id])) { 858 messages[attribute.id] = []; 859 } 860 861 if ($input.length) { 862 hasError = messages[attribute.id].length > 0; 863 } 864 865 return hasError; 866 }; 867 868 /** 869 * Updates the error summary. 870 * @param $form the form jQuery object 871 * @param messages array the validation error messages 872 */ 873 var updateSummary = function ($form, messages) { 874 var data = $form.data('yiiActiveForm'), 875 $summary = $form.find(data.settings.errorSummary), 876 $ul = $summary.find('ul').empty(); 877 878 if ($summary.length && messages) { 879 $.each(data.attributes, function () { 880 if ($.isArray(messages[this.id]) && messages[this.id].length) { 881 var error = $('<li/>'); 882 if (data.settings.encodeErrorSummary) { 883 error.text(messages[this.id][0]); 884 } else { 885 error.html(messages[this.id][0]); 886 } 887 $ul.append(error); 888 } 889 }); 890 $summary.toggle($ul.find('li').length > 0); 891 } 892 }; 893 894 var getValue = function ($form, attribute) { 895 var $input = findInput($form, attribute); 896 var type = $input.attr('type'); 897 if (type === 'checkbox' || type === 'radio') { 898 var $realInput = $input.filter(':checked'); 899 if ($realInput.length > 1) { 900 var values = []; 901 $realInput.each(function (index) { 902 values.push($($realInput.get(index)).val()); 903 }); 904 return values; 905 } 906 907 if (!$realInput.length) { 908 $realInput = $form.find('input[type=hidden][name="' + $input.attr('name') + '"]'); 909 } 910 911 return $realInput.val(); 912 } else { 913 return $input.val(); 914 } 915 }; 916 917 var findInput = function ($form, attribute) { 918 var $input = $form.find(attribute.input); 919 if ($input.length && $input[0].tagName.toLowerCase() === 'div') { 920 // checkbox list or radio list 921 return $input.find('input'); 922 } else { 923 return $input; 924 } 925 }; 926 927 var updateAriaInvalid = function ($form, attribute, hasError) { 928 if (attribute.updateAriaInvalid) { 929 $form.find(attribute.input).attr('aria-invalid', hasError ? 'true' : 'false'); 930 } 931 } 932})(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.