jquery.yiiactiveform.js 14 KB

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