yii.activeForm.js 35 KB

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