yii.activeForm.js 36 KB

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