yii.activeForm.js 36 KB

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