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