yii.activeForm.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  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. $form.find(this.container).addClass(data.settings.validatingCssClass);
  532. }
  533. });
  534. methods.validate.call($form);
  535. }, validationDelay ? validationDelay : 200);
  536. };
  537. /**
  538. * Compares two value whatever it objects, arrays or simple types
  539. * @param val1
  540. * @param val2
  541. * @returns boolean
  542. */
  543. var isEqual = function (val1, val2) {
  544. // objects
  545. if (val1 instanceof Object) {
  546. return isObjectsEqual(val1, val2)
  547. }
  548. // arrays
  549. if (Array.isArray(val1)) {
  550. return isArraysEqual(val1, val2);
  551. }
  552. // simple types
  553. return val1 === val2;
  554. };
  555. /**
  556. * Compares two objects
  557. * @param obj1
  558. * @param obj2
  559. * @returns boolean
  560. */
  561. var isObjectsEqual = function (obj1, obj2) {
  562. if (!(obj1 instanceof Object) || !(obj2 instanceof Object)) {
  563. return false;
  564. }
  565. var keys1 = Object.keys(obj1);
  566. var keys2 = Object.keys(obj2);
  567. if (keys1.length !== keys2.length) {
  568. return false;
  569. }
  570. for (var i = 0; i < keys1.length; i += 1) {
  571. if (!obj2.hasOwnProperty(keys1[i])) {
  572. return false;
  573. }
  574. if (obj1[keys1[i]] !== obj2[keys1[i]]) {
  575. return false;
  576. }
  577. }
  578. return true;
  579. };
  580. /**
  581. * Compares two arrays
  582. * @param arr1
  583. * @param arr2
  584. * @returns boolean
  585. */
  586. var isArraysEqual = function (arr1, arr2) {
  587. if (!Array.isArray(arr1) || !Array.isArray(arr2)) {
  588. return false;
  589. }
  590. if (arr1.length !== arr2.length) {
  591. return false;
  592. }
  593. for (var i = 0; i < arr1.length; i += 1) {
  594. if (arr1[i] !== arr2[i]) {
  595. return false;
  596. }
  597. }
  598. return true;
  599. };
  600. /**
  601. * Returns an array prototype with a shortcut method for adding a new deferred.
  602. * The context of the callback will be the deferred object so it can be resolved like ```this.resolve()```
  603. * @returns Array
  604. */
  605. var deferredArray = function () {
  606. var array = [];
  607. array.add = function (callback) {
  608. this.push(new $.Deferred(callback));
  609. };
  610. return array;
  611. };
  612. var buttonOptions = ['action', 'target', 'method', 'enctype'];
  613. /**
  614. * Returns current form options
  615. * @param $form
  616. * @returns object Object with button of form options
  617. */
  618. var getFormOptions = function ($form) {
  619. var attributes = {};
  620. for (var i = 0; i < buttonOptions.length; i++) {
  621. attributes[buttonOptions[i]] = $form.attr(buttonOptions[i]);
  622. }
  623. return attributes;
  624. };
  625. /**
  626. * Applies temporary form options related to submit button
  627. * @param $form the form jQuery object
  628. * @param $button the button jQuery object
  629. */
  630. var applyButtonOptions = function ($form, $button) {
  631. for (var i = 0; i < buttonOptions.length; i++) {
  632. var value = $button.attr('form' + buttonOptions[i]);
  633. if (value) {
  634. $form.attr(buttonOptions[i], value);
  635. }
  636. }
  637. };
  638. /**
  639. * Restores original form options
  640. * @param $form the form jQuery object
  641. */
  642. var restoreButtonOptions = function ($form) {
  643. var data = $form.data('yiiActiveForm');
  644. for (var i = 0; i < buttonOptions.length; i++) {
  645. $form.attr(buttonOptions[i], data.options[buttonOptions[i]] || null);
  646. }
  647. };
  648. /**
  649. * Updates the error messages and the input containers for all applicable attributes
  650. * @param $form the form jQuery object
  651. * @param messages array the validation error messages
  652. * @param submitting whether this method is called after validation triggered by form submission
  653. */
  654. var updateInputs = function ($form, messages, submitting) {
  655. var data = $form.data('yiiActiveForm');
  656. if (data === undefined) {
  657. return false;
  658. }
  659. var errorAttributes = [], $input;
  660. $.each(data.attributes, function () {
  661. var hasError = (submitting && updateInput($form, this, messages)) || (!submitting && attrHasError($form,
  662. this, messages));
  663. $input = findInput($form, this);
  664. if (!$input.is(':disabled') && !this.cancelled && hasError) {
  665. errorAttributes.push(this);
  666. }
  667. });
  668. $form.trigger(events.afterValidate, [messages, errorAttributes]);
  669. if (submitting) {
  670. updateSummary($form, messages);
  671. if (errorAttributes.length) {
  672. if (data.settings.scrollToError) {
  673. var h = $(document).height(), top = $form.find($.map(errorAttributes, function (attribute) {
  674. return attribute.input;
  675. }).join(',')).first().closest(':visible').offset().top - data.settings.scrollToErrorOffset;
  676. top = top < 0 ? 0 : (top > h ? h : top);
  677. var wtop = $(window).scrollTop();
  678. if (top < wtop || top > wtop + $(window).height()) {
  679. $(window).scrollTop(top);
  680. }
  681. }
  682. data.submitting = false;
  683. } else {
  684. data.validated = true;
  685. if (data.submitObject) {
  686. applyButtonOptions($form, data.submitObject);
  687. }
  688. $form.submit();
  689. if (data.submitObject) {
  690. restoreButtonOptions($form);
  691. }
  692. }
  693. } else {
  694. $.each(data.attributes, function () {
  695. if (!this.cancelled && (this.status === 2 || this.status === 3)) {
  696. updateInput($form, this, messages);
  697. }
  698. });
  699. }
  700. submitFinalize($form);
  701. };
  702. /**
  703. * Updates hidden field that represents clicked submit button.
  704. * @param $form the form jQuery object.
  705. */
  706. var updateHiddenButton = function ($form) {
  707. var data = $form.data('yiiActiveForm');
  708. var $button = data.submitObject || $form.find(':submit:first');
  709. // TODO: if the submission is caused by "change" event, it will not work
  710. if ($button.length && $button.attr('type') == 'submit' && $button.attr('name')) {
  711. // simulate button input value
  712. var $hiddenButton = $('input[type="hidden"][name="' + $button.attr('name') + '"]', $form);
  713. if (!$hiddenButton.length) {
  714. $('<input>').attr({
  715. type: 'hidden',
  716. name: $button.attr('name'),
  717. value: $button.attr('value')
  718. }).appendTo($form);
  719. } else {
  720. $hiddenButton.attr('value', $button.attr('value'));
  721. }
  722. }
  723. };
  724. /**
  725. * Updates the error message and the input container for a particular attribute.
  726. * @param $form the form jQuery object
  727. * @param attribute object the configuration for a particular attribute.
  728. * @param messages array the validation error messages
  729. * @return boolean whether there is a validation error for the specified attribute
  730. */
  731. var updateInput = function ($form, attribute, messages) {
  732. var data = $form.data('yiiActiveForm'),
  733. $input = findInput($form, attribute),
  734. hasError = attrHasError($form, attribute, messages);
  735. if (!$.isArray(messages[attribute.id])) {
  736. messages[attribute.id] = [];
  737. }
  738. attribute.status = 1;
  739. if ($input.length) {
  740. var $container = $form.find(attribute.container);
  741. var $error = $container.find(attribute.error);
  742. updateAriaInvalid($form, attribute, hasError);
  743. var $errorElement = data.settings.validationStateOn === 'input' ? $input : $container;
  744. if (hasError) {
  745. if (attribute.encodeError) {
  746. $error.text(messages[attribute.id][0]);
  747. } else {
  748. $error.html(messages[attribute.id][0]);
  749. }
  750. $errorElement.removeClass(data.settings.validatingCssClass + ' ' + data.settings.successCssClass)
  751. .addClass(data.settings.errorCssClass);
  752. } else {
  753. $error.empty();
  754. $errorElement.removeClass(data.settings.validatingCssClass + ' ' + data.settings.errorCssClass + ' ')
  755. .addClass(data.settings.successCssClass);
  756. }
  757. attribute.value = getValue($form, attribute);
  758. }
  759. $form.trigger(events.afterValidateAttribute, [attribute, messages[attribute.id]]);
  760. return hasError;
  761. };
  762. /**
  763. * Checks if a particular attribute has an error
  764. * @param $form the form jQuery object
  765. * @param attribute object the configuration for a particular attribute.
  766. * @param messages array the validation error messages
  767. * @return boolean whether there is a validation error for the specified attribute
  768. */
  769. var attrHasError = function ($form, attribute, messages) {
  770. var $input = findInput($form, attribute),
  771. hasError = false;
  772. if (!$.isArray(messages[attribute.id])) {
  773. messages[attribute.id] = [];
  774. }
  775. if ($input.length) {
  776. hasError = messages[attribute.id].length > 0;
  777. }
  778. return hasError;
  779. };
  780. /**
  781. * Updates the error summary.
  782. * @param $form the form jQuery object
  783. * @param messages array the validation error messages
  784. */
  785. var updateSummary = function ($form, messages) {
  786. var data = $form.data('yiiActiveForm'),
  787. $summary = $form.find(data.settings.errorSummary),
  788. $ul = $summary.find('ul').empty();
  789. if ($summary.length && messages) {
  790. $.each(data.attributes, function () {
  791. if ($.isArray(messages[this.id]) && messages[this.id].length) {
  792. var error = $('<li/>');
  793. if (data.settings.encodeErrorSummary) {
  794. error.text(messages[this.id][0]);
  795. } else {
  796. error.html(messages[this.id][0]);
  797. }
  798. $ul.append(error);
  799. }
  800. });
  801. $summary.toggle($ul.find('li').length > 0);
  802. }
  803. };
  804. var getValue = function ($form, attribute) {
  805. var $input = findInput($form, attribute);
  806. var type = $input.attr('type');
  807. if (type === 'checkbox' || type === 'radio') {
  808. var $realInput = $input.filter(':checked');
  809. if ($realInput.length > 1) {
  810. var values = [];
  811. $realInput.each(function (index) {
  812. values.push($($realInput.get(index)).val());
  813. });
  814. return values;
  815. }
  816. if (!$realInput.length) {
  817. $realInput = $form.find('input[type=hidden][name="' + $input.attr('name') + '"]');
  818. }
  819. return $realInput.val();
  820. } else {
  821. return $input.val();
  822. }
  823. };
  824. var findInput = function ($form, attribute) {
  825. var $input = $form.find(attribute.input);
  826. if ($input.length && $input[0].tagName.toLowerCase() === 'div') {
  827. // checkbox list or radio list
  828. return $input.find('input');
  829. } else {
  830. return $input;
  831. }
  832. };
  833. var updateAriaInvalid = function ($form, attribute, hasError) {
  834. if (attribute.updateAriaInvalid) {
  835. $form.find(attribute.input).attr('aria-invalid', hasError ? 'true' : 'false');
  836. }
  837. }
  838. })(window.jQuery);