jquery.yiiactiveform.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. /**
  2. * jQuery yiiactiveform plugin file.
  3. *
  4. * @author Qiang Xue <qiang.xue@gmail.com>
  5. * @link http://www.yiiframework.com/
  6. * @copyright 2008-2010 Yii Software LLC
  7. * @license http://www.yiiframework.com/license/
  8. * @since 1.1.1
  9. */
  10. (function ($) {
  11. /*
  12. * returns the value of the CActiveForm input field
  13. * performs additional checks to get proper values for checkbox / radiobutton / checkBoxList / radioButtonList
  14. * @param o object the jQuery object of the input element
  15. */
  16. var getAFValue = function (o) {
  17. var type,
  18. c = [];
  19. if (!o.length) {
  20. return undefined;
  21. }
  22. if (o[0].tagName.toLowerCase() === 'span') {
  23. o.find(':checked').each(function () {
  24. c.push(this.value);
  25. });
  26. return c.join(',');
  27. }
  28. type = o.attr('type');
  29. if (type === 'checkbox' || type === 'radio') {
  30. return o.filter(':checked').val();
  31. } else {
  32. return o.val();
  33. }
  34. };
  35. /**
  36. * yiiactiveform set function.
  37. * @param options map settings for the active form plugin. Please see {@link CActiveForm::options} for availablel options.
  38. */
  39. $.fn.yiiactiveform = function (options) {
  40. return this.each(function () {
  41. var settings = $.extend({}, $.fn.yiiactiveform.defaults, options || {}),
  42. $form = $(this);
  43. if (settings.validationUrl === undefined) {
  44. settings.validationUrl = $form.attr('action');
  45. }
  46. $.each(settings.attributes, function (i) {
  47. this.value = getAFValue($form.find('#' + this.inputID));
  48. settings.attributes[i] = $.extend({}, {
  49. validationDelay: settings.validationDelay,
  50. validateOnChange: settings.validateOnChange,
  51. validateOnType: settings.validateOnType,
  52. hideErrorMessage: settings.hideErrorMessage,
  53. inputContainer: settings.inputContainer,
  54. errorCssClass: settings.errorCssClass,
  55. successCssClass: settings.successCssClass,
  56. beforeValidateAttribute: settings.beforeValidateAttribute,
  57. afterValidateAttribute: settings.afterValidateAttribute,
  58. validatingCssClass: settings.validatingCssClass
  59. }, this);
  60. });
  61. $form.data('settings', settings);
  62. settings.submitting = false; // whether it is waiting for ajax submission result
  63. var validate = function (attribute, forceValidate) {
  64. if (forceValidate) {
  65. attribute.status = 2;
  66. }
  67. $.each(settings.attributes, function () {
  68. if (this.value !== getAFValue($form.find('#' + this.inputID))) {
  69. this.status = 2;
  70. forceValidate = true;
  71. }
  72. });
  73. if (!forceValidate) {
  74. return;
  75. }
  76. if (settings.timer !== undefined) {
  77. clearTimeout(settings.timer);
  78. }
  79. settings.timer = setTimeout(function () {
  80. if (settings.submitting || $form.is(':hidden')) {
  81. return;
  82. }
  83. if (attribute.beforeValidateAttribute === undefined || attribute.beforeValidateAttribute($form, attribute)) {
  84. $.each(settings.attributes, function () {
  85. if (this.status === 2) {
  86. this.status = 3;
  87. $.fn.yiiactiveform.getInputContainer(this, $form).addClass(this.validatingCssClass);
  88. }
  89. });
  90. $.fn.yiiactiveform.validate($form, function (data) {
  91. var hasError = false;
  92. $.each(settings.attributes, function () {
  93. if (this.status === 2 || this.status === 3) {
  94. hasError = $.fn.yiiactiveform.updateInput(this, data, $form) || hasError;
  95. }
  96. });
  97. if (attribute.afterValidateAttribute !== undefined) {
  98. attribute.afterValidateAttribute($form, attribute, data, hasError);
  99. }
  100. });
  101. }
  102. }, attribute.validationDelay);
  103. };
  104. $.each(settings.attributes, function (i, attribute) {
  105. if (this.validateOnChange) {
  106. $form.find('#' + this.inputID).change(function () {
  107. validate(attribute, false);
  108. }).blur(function () {
  109. if (attribute.status !== 2 && attribute.status !== 3) {
  110. validate(attribute, !attribute.status);
  111. }
  112. });
  113. }
  114. if (this.validateOnType) {
  115. $form.find('#' + this.inputID).keyup(function () {
  116. if (attribute.value !== getAFValue($(this))) {
  117. validate(attribute, false);
  118. }
  119. });
  120. }
  121. });
  122. if (settings.validateOnSubmit) {
  123. $form.on('mouseup keyup', ':submit', function () {
  124. $form.data('submitObject', $(this));
  125. });
  126. var validated = false;
  127. $form.submit(function () {
  128. if (validated) {
  129. validated = false;
  130. return true;
  131. }
  132. if (settings.timer !== undefined) {
  133. clearTimeout(settings.timer);
  134. }
  135. settings.submitting = true;
  136. if (settings.beforeValidate === undefined || settings.beforeValidate($form)) {
  137. $.fn.yiiactiveform.validate($form, function (data) {
  138. var hasError = false;
  139. $.each(settings.attributes, function () {
  140. hasError = $.fn.yiiactiveform.updateInput(this, data, $form) || hasError;
  141. });
  142. $.fn.yiiactiveform.updateSummary($form, data);
  143. if (settings.afterValidate === undefined || settings.afterValidate($form, data, hasError)) {
  144. if (!hasError) {
  145. validated = true;
  146. var $button = $form.data('submitObject') || $form.find(':submit:first');
  147. // TODO: if the submission is caused by "change" event, it will not work
  148. if ($button.length) {
  149. $button.click();
  150. } else { // no submit button in the form
  151. $form.submit();
  152. }
  153. return;
  154. }
  155. }
  156. settings.submitting = false;
  157. });
  158. } else {
  159. settings.submitting = false;
  160. }
  161. return false;
  162. });
  163. }
  164. /*
  165. * In case of reseting the form we need to reset error messages
  166. * NOTE1: $form.reset - does not exist
  167. * NOTE2: $form.on('reset', ...) does not work
  168. */
  169. $form.bind('reset', function () {
  170. /*
  171. * because we bind directly to a form reset event, not to a reset button (that could or could not exist),
  172. * when this function is executed form elements values have not been reset yet,
  173. * because of that we use the setTimeout
  174. */
  175. setTimeout(function () {
  176. $.each(settings.attributes, function () {
  177. this.status = 0;
  178. var $error = $form.find('#' + this.errorID),
  179. $container = $.fn.yiiactiveform.getInputContainer(this, $form);
  180. $container.removeClass(
  181. this.validatingCssClass + ' ' +
  182. this.errorCssClass + ' ' +
  183. this.successCssClass
  184. );
  185. $error.html('').hide();
  186. /*
  187. * without the setTimeout() we would get here the current entered value before the reset instead of the reseted value
  188. */
  189. this.value = getAFValue($form.find('#' + this.inputID));
  190. });
  191. /*
  192. * If the form is submited (non ajax) with errors, labels and input gets the class 'error'
  193. */
  194. $form.find('label, :input').each(function () {
  195. $(this).removeClass(settings.errorCss);
  196. });
  197. $('#' + settings.summaryID).hide().find('ul').html('');
  198. //.. set to initial focus on reset
  199. if (settings.focus !== undefined && !window.location.hash) {
  200. $form.find(settings.focus).focus();
  201. }
  202. }, 1);
  203. });
  204. /*
  205. * set to initial focus
  206. */
  207. if (settings.focus !== undefined && !window.location.hash) {
  208. $form.find(settings.focus).focus();
  209. }
  210. });
  211. };
  212. /**
  213. * Returns the container element of the specified attribute.
  214. * @param attribute object the configuration for a particular attribute.
  215. * @param form the form jQuery object
  216. * @return jQuery the jQuery representation of the container
  217. */
  218. $.fn.yiiactiveform.getInputContainer = function (attribute, form) {
  219. if (attribute.inputContainer === undefined) {
  220. return form.find('#' + attribute.inputID).closest('div');
  221. } else {
  222. return form.find(attribute.inputContainer).filter(':has("#' + attribute.inputID + '")');
  223. }
  224. };
  225. /**
  226. * updates the error message and the input container for a particular attribute.
  227. * @param attribute object the configuration for a particular attribute.
  228. * @param messages array the json data obtained from the ajax validation request
  229. * @param form the form jQuery object
  230. * @return boolean whether there is a validation error for the specified attribute
  231. */
  232. $.fn.yiiactiveform.updateInput = function (attribute, messages, form) {
  233. attribute.status = 1;
  234. var $error, $container,
  235. hasError = false,
  236. $el = form.find('#' + attribute.inputID),
  237. errorCss = form.data('settings').errorCss;
  238. if ($el.length) {
  239. hasError = messages !== null && $.isArray(messages[attribute.id]) && messages[attribute.id].length > 0;
  240. $error = form.find('#' + attribute.errorID);
  241. $container = $.fn.yiiactiveform.getInputContainer(attribute, form);
  242. $container.removeClass(
  243. attribute.validatingCssClass + ' ' +
  244. attribute.errorCssClass + ' ' +
  245. attribute.successCssClass
  246. );
  247. $container.find('label, :input').each(function () {
  248. $(this).removeClass(errorCss);
  249. });
  250. if (hasError) {
  251. $error.html(messages[attribute.id][0]);
  252. $container.addClass(attribute.errorCssClass);
  253. } else if (attribute.enableAjaxValidation || attribute.clientValidation) {
  254. $container.addClass(attribute.successCssClass);
  255. }
  256. if (!attribute.hideErrorMessage) {
  257. $error.toggle(hasError);
  258. }
  259. attribute.value = getAFValue($el);
  260. }
  261. return hasError;
  262. };
  263. /**
  264. * updates the error summary, if any.
  265. * @param form jquery the jquery representation of the form
  266. * @param messages array the json data obtained from the ajax validation request
  267. */
  268. $.fn.yiiactiveform.updateSummary = function (form, messages) {
  269. var settings = $(form).data('settings'),
  270. content = '';
  271. if (settings.summaryID === undefined) {
  272. return;
  273. }
  274. if (messages) {
  275. var summaryAttributes = [];
  276. for (var i in settings.attributes) {
  277. if (settings.attributes[i].summary) {
  278. summaryAttributes.push(settings.attributes[i].id);
  279. }
  280. }
  281. $.each(settings.attributes, function () {
  282. if ($.inArray(this.id, summaryAttributes) !== -1 && $.isArray(messages[this.id])) {
  283. $.each(messages[this.id], function (j, message) {
  284. content = content + '<li>' + message + '</li>';
  285. });
  286. }
  287. });
  288. }
  289. $('#' + settings.summaryID).toggle(content !== '').find('ul').html(content);
  290. };
  291. /**
  292. * Performs the ajax validation request.
  293. * This method is invoked internally to trigger the ajax validation.
  294. * @param form jquery the jquery representation of the form
  295. * @param successCallback function the function to be invoked if the ajax request succeeds
  296. * @param errorCallback function the function to be invoked if the ajax request fails
  297. */
  298. $.fn.yiiactiveform.validate = function (form, successCallback, errorCallback) {
  299. var $form = $(form),
  300. settings = $form.data('settings'),
  301. needAjaxValidation = false,
  302. messages = {};
  303. $.each(settings.attributes, function () {
  304. var value,
  305. msg = [];
  306. if (this.clientValidation !== undefined && (settings.submitting || this.status === 2 || this.status === 3)) {
  307. value = getAFValue($form.find('#' + this.inputID));
  308. this.clientValidation(value, msg, this);
  309. if (msg.length) {
  310. messages[this.id] = msg;
  311. }
  312. }
  313. if (this.enableAjaxValidation && !msg.length && (settings.submitting || this.status === 2 || this.status === 3)) {
  314. needAjaxValidation = true;
  315. }
  316. });
  317. if (!needAjaxValidation || settings.submitting && !$.isEmptyObject(messages)) {
  318. if (settings.submitting) {
  319. // delay callback so that the form can be submitted without problem
  320. setTimeout(function () {
  321. successCallback(messages);
  322. }, 200);
  323. } else {
  324. successCallback(messages);
  325. }
  326. return;
  327. }
  328. var $button = $form.data('submitObject'),
  329. extData = '&' + settings.ajaxVar + '=' + $form.attr('id');
  330. if ($button && $button.length) {
  331. extData += '&' + $button.attr('name') + '=' + $button.attr('value');
  332. }
  333. $.ajax({
  334. url: settings.validationUrl,
  335. type: $form.attr('method'),
  336. data: $form.serialize() + extData,
  337. dataType: 'json',
  338. success: function (data) {
  339. if (data !== null && typeof data === 'object') {
  340. $.each(settings.attributes, function () {
  341. if (!this.enableAjaxValidation) {
  342. delete data[this.id];
  343. }
  344. });
  345. successCallback($.extend({}, messages, data));
  346. } else {
  347. successCallback(messages);
  348. }
  349. },
  350. error: function () {
  351. if (errorCallback !== undefined) {
  352. errorCallback();
  353. }
  354. }
  355. });
  356. };
  357. /**
  358. * Returns the configuration for the specified form.
  359. * The configuration contains all needed information to perform ajax-based validation.
  360. * @param form jquery the jquery representation of the form
  361. * @return object the configuration for the specified form.
  362. */
  363. $.fn.yiiactiveform.getSettings = function (form) {
  364. return $(form).data('settings');
  365. };
  366. $.fn.yiiactiveform.defaults = {
  367. ajaxVar: 'ajax',
  368. validationUrl: undefined,
  369. validationDelay: 200,
  370. validateOnSubmit: false,
  371. validateOnChange: true,
  372. validateOnType: false,
  373. hideErrorMessage: false,
  374. inputContainer: undefined,
  375. errorCss: 'error',
  376. errorCssClass: 'error',
  377. successCssClass: 'success',
  378. validatingCssClass: 'validating',
  379. summaryID: undefined,
  380. timer: undefined,
  381. beforeValidateAttribute: undefined, // function (form, attribute) | boolean
  382. afterValidateAttribute: undefined, // function (form, attribute, data, hasError)
  383. beforeValidate: undefined, // function (form) | boolean
  384. afterValidate: undefined, // function (form, data, hasError) | boolean
  385. focus: undefined, // jquery selector that indicates which element to receive input focus initially
  386. /**
  387. * list of attributes to be validated. Each array element is of the following structure:
  388. * {
  389. * id: 'ModelClass_attribute', // the unique attribute ID
  390. * model: 'ModelClass', // the model class name
  391. * name: 'name', // attribute name
  392. * inputID: 'input-tag-id',
  393. * errorID: 'error-tag-id',
  394. * value: undefined,
  395. * status: 0, // 0: empty, not entered before, 1: validated, 2: pending validation, 3: validating
  396. * validationDelay: 200,
  397. * validateOnChange: true,
  398. * validateOnType: false,
  399. * hideErrorMessage: false,
  400. * inputContainer: undefined,
  401. * errorCssClass: 'error',
  402. * successCssClass: 'success',
  403. * validatingCssClass: 'validating',
  404. * enableAjaxValidation: true,
  405. * enableClientValidation: true,
  406. * clientValidation: undefined, // function (value, messages, attribute) | client-side validation
  407. * beforeValidateAttribute: undefined, // function (form, attribute) | boolean
  408. * afterValidateAttribute: undefined, // function (form, attribute, data, hasError)
  409. * }
  410. */
  411. attributes: []
  412. };
  413. })(jQuery);