jqBootstrapValidation.js 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217
  1. /*! jqBootstrapValidation - v1.3.7 - 2013-05-07
  2. * http://reactiveraven.github.com/jqBootstrapValidation
  3. * Copyright (c) 2013 David Godfrey; Licensed MIT */
  4. (function ($) {
  5. var createdElements = [];
  6. var defaults = {
  7. options: {
  8. prependExistingHelpBlock: false,
  9. sniffHtml: true, // sniff for 'required', 'maxlength', etc
  10. preventSubmit: true, // stop the form submit event from firing if validation fails
  11. submitError: false, // function called if there is an error when trying to submit
  12. submitSuccess: false, // function called just before a successful submit event is sent to the server
  13. semanticallyStrict: false, // set to true to tidy up generated HTML output
  14. removeSuccess : true,
  15. bindEvents: [],
  16. autoAdd: {
  17. helpBlocks: true
  18. },
  19. filter: function () {
  20. // return $(this).is(":visible"); // only validate elements you can see
  21. return true; // validate everything
  22. }
  23. },
  24. methods: {
  25. init: function (options) {
  26. // Get a clean copy of the defaults for extending
  27. var settings = $.extend(true, {}, defaults);
  28. // Set up the options based on the input
  29. settings.options = $.extend(true, settings.options, options);
  30. var $siblingElements = this;
  31. var uniqueForms = $.unique(
  32. $siblingElements.map(function () {
  33. return $(this).parents("form")[0];
  34. }).toArray()
  35. );
  36. $(uniqueForms).bind("submit.validationSubmit", function (e) {
  37. var $form = $(this);
  38. var warningsFound = 0;
  39. // Get all inputs
  40. var $allInputs = $form.find("input,textarea,select").not("[type=submit],[type=image]").filter(settings.options.filter);
  41. var $allControlGroups = $form.find(".form-group");
  42. // Only trigger validation on the ones that actually _have_ validation
  43. var $inputsWithValidators = $allInputs.filter(function () {
  44. return $(this).triggerHandler("getValidatorCount.validation") > 0;
  45. });
  46. $inputsWithValidators.trigger("submit.validation");
  47. // But all of them are out-of-focus now, because we're submitting.
  48. $allInputs.trigger("validationLostFocus.validation");
  49. // Okay, now check each controlgroup for errors (or warnings)
  50. $allControlGroups.each(function (i, el) {
  51. var $controlGroup = $(el);
  52. if ($controlGroup.hasClass("issue") || $controlGroup.hasClass("error")) {
  53. $controlGroup.removeClass("issue").addClass("error");
  54. warningsFound++;
  55. }
  56. });
  57. if (warningsFound) {
  58. // If we found any warnings, maybe we should prevent the submit
  59. // event, and trigger 'submitError' (if they're set up)
  60. if (settings.options.preventSubmit) {
  61. e.preventDefault();
  62. e.stopImmediatePropagation();
  63. }
  64. $form.addClass("error");
  65. if ($.isFunction(settings.options.submitError)) {
  66. settings.options.submitError($form, e, $inputsWithValidators.jqBootstrapValidation("collectErrors", true));
  67. }
  68. } else {
  69. // Woo! No errors! We can pass the submit event to submitSuccess
  70. // (if it has been set up)
  71. $form.removeClass("error");
  72. if ($.isFunction(settings.options.submitSuccess)) {
  73. settings.options.submitSuccess($form, e);
  74. }
  75. }
  76. });
  77. return this.each(function () {
  78. // Get references to everything we're interested in
  79. var $this = $(this),
  80. $controlGroup = $this.parents(".form-group").first(),
  81. $helpBlock = $controlGroup.find(".help-block").first(),
  82. $form = $this.parents("form").first(),
  83. validatorNames = [];
  84. // create message container if not exists
  85. if (!$helpBlock.length && settings.options.autoAdd && settings.options.autoAdd.helpBlocks) {
  86. $helpBlock = $('<div class="help-block" />');
  87. $controlGroup.find('.controls').append($helpBlock);
  88. createdElements.push($helpBlock[0]);
  89. }
  90. // =============================================================
  91. // SNIFF HTML FOR VALIDATORS
  92. // =============================================================
  93. // *snort sniff snuffle*
  94. if (settings.options.sniffHtml) {
  95. var message;
  96. // ---------------------------------------------------------
  97. // PATTERN
  98. // ---------------------------------------------------------
  99. if ($this.data("validationPatternPattern")) {
  100. $this.attr("pattern", $this.data("validationPatternPattern"));
  101. }
  102. if ($this.attr("pattern") !== undefined) {
  103. message = "Not in the expected format<!-- data-validation-pattern-message to override -->";
  104. if ($this.data("validationPatternMessage")) {
  105. message = $this.data("validationPatternMessage");
  106. }
  107. $this.data("validationPatternMessage", message);
  108. $this.data("validationPatternRegex", $this.attr("pattern"));
  109. }
  110. // ---------------------------------------------------------
  111. // MAX
  112. // ---------------------------------------------------------
  113. if ($this.attr("max") !== undefined || $this.attr("aria-valuemax") !== undefined) {
  114. var max = ($this.attr("max") !== undefined ? $this.attr("max") : $this.attr("aria-valuemax"));
  115. message = "Too high: Maximum of '" + max + "'<!-- data-validation-max-message to override -->";
  116. if ($this.data("validationMaxMessage")) {
  117. message = $this.data("validationMaxMessage");
  118. }
  119. $this.data("validationMaxMessage", message);
  120. $this.data("validationMaxMax", max);
  121. }
  122. // ---------------------------------------------------------
  123. // MIN
  124. // ---------------------------------------------------------
  125. if ($this.attr("min") !== undefined || $this.attr("aria-valuemin") !== undefined) {
  126. var min = ($this.attr("min") !== undefined ? $this.attr("min") : $this.attr("aria-valuemin"));
  127. message = "Too low: Minimum of '" + min + "'<!-- data-validation-min-message to override -->";
  128. if ($this.data("validationMinMessage")) {
  129. message = $this.data("validationMinMessage");
  130. }
  131. $this.data("validationMinMessage", message);
  132. $this.data("validationMinMin", min);
  133. }
  134. // ---------------------------------------------------------
  135. // MAXLENGTH
  136. // ---------------------------------------------------------
  137. if ($this.attr("maxlength") !== undefined) {
  138. message = "Too long: Maximum of '" + $this.attr("maxlength") + "' characters<!-- data-validation-maxlength-message to override -->";
  139. if ($this.data("validationMaxlengthMessage")) {
  140. message = $this.data("validationMaxlengthMessage");
  141. }
  142. $this.data("validationMaxlengthMessage", message);
  143. $this.data("validationMaxlengthMaxlength", $this.attr("maxlength"));
  144. }
  145. // ---------------------------------------------------------
  146. // MINLENGTH
  147. // ---------------------------------------------------------
  148. if ($this.attr("minlength") !== undefined) {
  149. message = "Too short: Minimum of '" + $this.attr("minlength") + "' characters<!-- data-validation-minlength-message to override -->";
  150. if ($this.data("validationMinlengthMessage")) {
  151. message = $this.data("validationMinlengthMessage");
  152. }
  153. $this.data("validationMinlengthMessage", message);
  154. $this.data("validationMinlengthMinlength", $this.attr("minlength"));
  155. }
  156. // ---------------------------------------------------------
  157. // REQUIRED
  158. // ---------------------------------------------------------
  159. if ($this.attr("required") !== undefined || $this.attr("aria-required") !== undefined) {
  160. message = settings.builtInValidators.required.message;
  161. if ($this.data("validationRequiredMessage")) {
  162. message = $this.data("validationRequiredMessage");
  163. }
  164. $this.data("validationRequiredMessage", message);
  165. }
  166. // ---------------------------------------------------------
  167. // NUMBER
  168. // ---------------------------------------------------------
  169. if ($this.attr("type") !== undefined && $this.attr("type").toLowerCase() === "number") {
  170. message = settings.validatorTypes.number.message; // TODO: fix this
  171. if ($this.data("validationNumberMessage")) {
  172. message = $this.data("validationNumberMessage");
  173. }
  174. $this.data("validationNumberMessage", message);
  175. var step = settings.validatorTypes.number.step; // TODO: and this
  176. if ($this.data("validationNumberStep")) {
  177. step = $this.data("validationNumberStep");
  178. }
  179. $this.data("validationNumberStep", step);
  180. var decimal = settings.validatorTypes.number.decimal;
  181. if ($this.data("validationNumberDecimal")) {
  182. decimal = $this.data("validationNumberDecimal");
  183. }
  184. $this.data("validationNumberDecimal", decimal);
  185. }
  186. // ---------------------------------------------------------
  187. // EMAIL
  188. // ---------------------------------------------------------
  189. if ($this.attr("type") !== undefined && $this.attr("type").toLowerCase() === "email") {
  190. message = "Not a valid email address<!-- data-validation-email-message to override -->";
  191. if ($this.data("validationEmailMessage")) {
  192. message = $this.data("validationEmailMessage");
  193. }
  194. $this.data("validationEmailMessage", message);
  195. }
  196. // ---------------------------------------------------------
  197. // MINCHECKED
  198. // ---------------------------------------------------------
  199. if ($this.attr("minchecked") !== undefined) {
  200. message = "Not enough options checked; Minimum of '" + $this.attr("minchecked") + "' required<!-- data-validation-minchecked-message to override -->";
  201. if ($this.data("validationMincheckedMessage")) {
  202. message = $this.data("validationMincheckedMessage");
  203. }
  204. $this.data("validationMincheckedMessage", message);
  205. $this.data("validationMincheckedMinchecked", $this.attr("minchecked"));
  206. }
  207. // ---------------------------------------------------------
  208. // MAXCHECKED
  209. // ---------------------------------------------------------
  210. if ($this.attr("maxchecked") !== undefined) {
  211. message = "Too many options checked; Maximum of '" + $this.attr("maxchecked") + "' required<!-- data-validation-maxchecked-message to override -->";
  212. if ($this.data("validationMaxcheckedMessage")) {
  213. message = $this.data("validationMaxcheckedMessage");
  214. }
  215. $this.data("validationMaxcheckedMessage", message);
  216. $this.data("validationMaxcheckedMaxchecked", $this.attr("maxchecked"));
  217. }
  218. }
  219. // =============================================================
  220. // COLLECT VALIDATOR NAMES
  221. // =============================================================
  222. // Get named validators
  223. if ($this.data("validation") !== undefined) {
  224. validatorNames = $this.data("validation").split(",");
  225. }
  226. // Get extra ones defined on the element's data attributes
  227. $.each($this.data(), function (i, el) {
  228. var parts = i.replace(/([A-Z])/g, ",$1").split(",");
  229. if (parts[0] === "validation" && parts[1]) {
  230. validatorNames.push(parts[1]);
  231. }
  232. });
  233. // =============================================================
  234. // NORMALISE VALIDATOR NAMES
  235. // =============================================================
  236. var validatorNamesToInspect = validatorNames;
  237. var newValidatorNamesToInspect = [];
  238. var uppercaseEachValidatorName = function (i, el) {
  239. validatorNames[i] = formatValidatorName(el);
  240. };
  241. var inspectValidators = function (i, el) {
  242. if ($this.data("validation" + el + "Shortcut") !== undefined) {
  243. // Are these custom validators?
  244. // Pull them out!
  245. $.each($this.data("validation" + el + "Shortcut").split(","), function (i2, el2) {
  246. newValidatorNamesToInspect.push(el2);
  247. });
  248. } else if (settings.builtInValidators[el.toLowerCase()]) {
  249. // Is this a recognised built-in?
  250. // Pull it out!
  251. var validator = settings.builtInValidators[el.toLowerCase()];
  252. if (validator.type.toLowerCase() === "shortcut") {
  253. $.each(validator.shortcut.split(","), function (i, el) {
  254. el = formatValidatorName(el);
  255. newValidatorNamesToInspect.push(el);
  256. validatorNames.push(el);
  257. });
  258. }
  259. }
  260. };
  261. do // repeatedly expand 'shortcut' validators into their real validators
  262. {
  263. // Uppercase only the first letter of each name
  264. $.each(validatorNames, uppercaseEachValidatorName);
  265. // Remove duplicate validator names
  266. validatorNames = $.unique(validatorNames);
  267. // Pull out the new validator names from each shortcut
  268. newValidatorNamesToInspect = [];
  269. $.each(validatorNamesToInspect, inspectValidators);
  270. validatorNamesToInspect = newValidatorNamesToInspect;
  271. } while (validatorNamesToInspect.length > 0);
  272. // =============================================================
  273. // SET UP VALIDATOR ARRAYS
  274. // =============================================================
  275. /* We're gonna generate something like
  276. *
  277. * {
  278. * "regex": [
  279. * { -- a validator object here --},
  280. * { -- a validator object here --}
  281. * ],
  282. * "required": [
  283. * { -- a validator object here --},
  284. * { -- a validator object here --}
  285. * ]
  286. * }
  287. *
  288. * with a few more entries.
  289. *
  290. * Because we only add a few validators to each field, most of the
  291. * keys will be empty arrays with no validator objects in them, and
  292. * thats fine.
  293. */
  294. var validators = {};
  295. $.each(validatorNames, function (i, el) {
  296. // Set up the 'override' message
  297. var message = $this.data("validation" + el + "Message");
  298. var hasOverrideMessage = !!message;
  299. var foundValidator = false;
  300. if (!message) {
  301. message = "'" + el + "' validation failed <!-- Add attribute 'data-validation-" + el.toLowerCase() + "-message' to input to change this message -->";
  302. }
  303. $.each(
  304. settings.validatorTypes,
  305. function (validatorType, validatorTemplate) {
  306. if (validators[validatorType] === undefined) {
  307. validators[validatorType] = [];
  308. }
  309. if (!foundValidator && $this.data("validation" + el + formatValidatorName(validatorTemplate.name)) !== undefined) {
  310. var initted = validatorTemplate.init($this, el);
  311. if (hasOverrideMessage) {
  312. initted.message = message;
  313. }
  314. validators[validatorType].push(
  315. $.extend(
  316. true,
  317. {
  318. name: formatValidatorName(validatorTemplate.name),
  319. message: message
  320. },
  321. initted
  322. )
  323. );
  324. foundValidator = true;
  325. }
  326. }
  327. );
  328. if (!foundValidator && settings.builtInValidators[el.toLowerCase()]) {
  329. var validator = $.extend(true, {}, settings.builtInValidators[el.toLowerCase()]);
  330. if (hasOverrideMessage) {
  331. validator.message = message;
  332. }
  333. var validatorType = validator.type.toLowerCase();
  334. if (validatorType === "shortcut") {
  335. foundValidator = true;
  336. } else {
  337. $.each(
  338. settings.validatorTypes,
  339. function (validatorTemplateType, validatorTemplate) {
  340. if (validators[validatorTemplateType] === undefined) {
  341. validators[validatorTemplateType] = [];
  342. }
  343. if (!foundValidator && validatorType === validatorTemplateType.toLowerCase()) {
  344. $this.data(
  345. "validation" + el + formatValidatorName(validatorTemplate.name),
  346. validator[validatorTemplate.name.toLowerCase()]
  347. );
  348. validators[validatorType].push(
  349. $.extend(
  350. validator,
  351. validatorTemplate.init($this, el)
  352. )
  353. );
  354. foundValidator = true;
  355. }
  356. }
  357. );
  358. }
  359. }
  360. if (!foundValidator) {
  361. $.error("Cannot find validation info for '" + el + "'");
  362. }
  363. });
  364. // =============================================================
  365. // STORE FALLBACK VALUES
  366. // =============================================================
  367. $helpBlock.data(
  368. "original-contents",
  369. (
  370. $helpBlock.data("original-contents") ?
  371. $helpBlock.data("original-contents") :
  372. $helpBlock.html()
  373. )
  374. );
  375. $helpBlock.data(
  376. "original-role",
  377. (
  378. $helpBlock.data("original-role") ?
  379. $helpBlock.data("original-role") :
  380. $helpBlock.attr("role")
  381. )
  382. );
  383. $controlGroup.data(
  384. "original-classes",
  385. (
  386. $controlGroup.data("original-clases") ?
  387. $controlGroup.data("original-classes") :
  388. $controlGroup.attr("class")
  389. )
  390. );
  391. $this.data(
  392. "original-aria-invalid",
  393. (
  394. $this.data("original-aria-invalid") ?
  395. $this.data("original-aria-invalid") :
  396. $this.attr("aria-invalid")
  397. )
  398. );
  399. // =============================================================
  400. // VALIDATION
  401. // =============================================================
  402. $this.bind(
  403. "validation.validation",
  404. function (event, params) {
  405. var value = getValue($this);
  406. // Get a list of the errors to apply
  407. var errorsFound = [];
  408. $.each(validators, function (validatorType, validatorTypeArray) {
  409. if (
  410. value || // has a truthy value
  411. value.length || // not an empty string
  412. ( // am including empty values
  413. (
  414. params &&
  415. params.includeEmpty
  416. ) || !!settings.validatorTypes[validatorType].includeEmpty
  417. ) ||
  418. ( // validator is blocking submit
  419. !!settings.validatorTypes[validatorType].blockSubmit &&
  420. params && !!params.submitting
  421. )
  422. ) {
  423. $.each(
  424. validatorTypeArray,
  425. function (i, validator) {
  426. if (settings.validatorTypes[validatorType].validate($this, value, validator)) {
  427. errorsFound.push(validator.message);
  428. }
  429. }
  430. );
  431. }
  432. });
  433. return errorsFound;
  434. }
  435. );
  436. $this.bind(
  437. "getValidators.validation",
  438. function () {
  439. return validators;
  440. }
  441. );
  442. var numValidators = 0;
  443. $.each(validators, function (i, el) {
  444. numValidators += el.length;
  445. });
  446. $this.bind("getValidatorCount.validation", function () {
  447. return numValidators;
  448. });
  449. // =============================================================
  450. // WATCH FOR CHANGES
  451. // =============================================================
  452. $this.bind(
  453. "submit.validation",
  454. function () {
  455. return $this.triggerHandler("change.validation", {submitting: true});
  456. }
  457. );
  458. $this.bind(
  459. (
  460. settings.options.bindEvents.length > 0 ?
  461. settings.options.bindEvents :
  462. [
  463. "keyup",
  464. "focus",
  465. "blur",
  466. "click",
  467. "keydown",
  468. "keypress",
  469. "change"
  470. ]
  471. ).concat(["revalidate"]).join(".validation ") + ".validation",
  472. function (e, params) {
  473. var value = getValue($this);
  474. var errorsFound = [];
  475. if (params && !!params.submitting) {
  476. $controlGroup.data("jqbvIsSubmitting", true);
  477. } else if (e.type !== "revalidate") {
  478. $controlGroup.data("jqbvIsSubmitting", false);
  479. }
  480. var formIsSubmitting = !!$controlGroup.data("jqbvIsSubmitting");
  481. $controlGroup.find("input,textarea,select").not('[type=submit]').each(function (i, el) {
  482. var oldCount = errorsFound.length;
  483. $.each($(el).triggerHandler("validation.validation", params) || [], function (j, message) {
  484. errorsFound.push(message);
  485. });
  486. if (errorsFound.length > oldCount) {
  487. $(el).attr("aria-invalid", "true");
  488. } else {
  489. var original = $this.data("original-aria-invalid");
  490. $(el).attr("aria-invalid", (original !== undefined ? original : false));
  491. }
  492. });
  493. $form.find("input,select,textarea").not($this).not("[name=\"" + $this.attr("name") + "\"]").trigger("validationLostFocus.validation");
  494. errorsFound = $.unique(errorsFound.sort());
  495. // Were there any errors?
  496. if (errorsFound.length) {
  497. // Better flag it up as a warning.
  498. $controlGroup.removeClass("validate error issue").addClass(formIsSubmitting ? "error" : "issue");
  499. // How many errors did we find?
  500. if (settings.options.semanticallyStrict && errorsFound.length === 1) {
  501. // Only one? Being strict? Just output it.
  502. $helpBlock.html(errorsFound[0] +
  503. ( settings.options.prependExistingHelpBlock ? $helpBlock.data("original-contents") : "" ));
  504. } else {
  505. // Multiple? Being sloppy? Glue them together into an UL.
  506. $helpBlock.html("<ul role=\"alert\"><li>" + errorsFound.join("</li><li>") + "</li></ul>" +
  507. ( settings.options.prependExistingHelpBlock ? $helpBlock.data("original-contents") : "" ));
  508. }
  509. } else {
  510. $controlGroup.removeClass("issue error validate");
  511. if (value.length > 0) {
  512. $controlGroup.addClass("validate");
  513. }
  514. $helpBlock.html($helpBlock.data("original-contents"));
  515. }
  516. if (e.type === "blur") {
  517. if( settings.options.removeSuccess ){
  518. // $controlGroup.removeClass("validate");
  519. }
  520. }
  521. }
  522. );
  523. $this.bind("validationLostFocus.validation", function () {
  524. if( settings.options.removeSuccess ){
  525. // $controlGroup.removeClass("validate");
  526. }
  527. });
  528. });
  529. },
  530. destroy: function () {
  531. return this.each(
  532. function () {
  533. var
  534. $this = $(this),
  535. $controlGroup = $this.parents(".form-group").first(),
  536. $helpBlock = $controlGroup.find(".help-block").first(),
  537. $form = $this.parents("form").first();
  538. // remove our events
  539. $this.unbind('.validation'); // events are namespaced.
  540. $form.unbind(".validationSubmit");
  541. // reset help text
  542. $helpBlock.html($helpBlock.data("original-contents"));
  543. // reset classes
  544. $controlGroup.attr("class", $controlGroup.data("original-classes"));
  545. // reset aria
  546. $this.attr("aria-invalid", $this.data("original-aria-invalid"));
  547. // reset role
  548. $helpBlock.attr("role", $this.data("original-role"));
  549. // remove all elements we created
  550. if ($.inArray($helpBlock[0], createdElements) > -1) {
  551. $helpBlock.remove();
  552. }
  553. }
  554. );
  555. },
  556. collectErrors: function (includeEmpty) {
  557. var errorMessages = {};
  558. this.each(function (i, el) {
  559. var $el = $(el);
  560. var name = $el.attr("name");
  561. var errors = $el.triggerHandler("validation.validation", {includeEmpty: true});
  562. errorMessages[name] = $.extend(true, errors, errorMessages[name]);
  563. });
  564. $.each(errorMessages, function (i, el) {
  565. if (el.length === 0) {
  566. delete errorMessages[i];
  567. }
  568. });
  569. return errorMessages;
  570. },
  571. hasErrors: function () {
  572. var errorMessages = [];
  573. this.find('input,select,textarea').add(this).each(function (i, el) {
  574. errorMessages = errorMessages.concat(
  575. $(el).triggerHandler("getValidators.validation") ? $(el).triggerHandler("validation.validation", {submitting: true}) : []
  576. );
  577. });
  578. return (errorMessages.length > 0);
  579. },
  580. override: function (newDefaults) {
  581. defaults = $.extend(true, defaults, newDefaults);
  582. }
  583. },
  584. validatorTypes: {
  585. callback: {
  586. name: "callback",
  587. init: function ($this, name) {
  588. var result = {
  589. validatorName: name,
  590. callback: $this.data("validation" + name + "Callback"),
  591. lastValue: $this.val(),
  592. lastValid: true,
  593. lastFinished: true
  594. };
  595. var message = "Not valid";
  596. if ($this.data("validation" + name + "Message")) {
  597. message = $this.data("validation" + name + "Message");
  598. }
  599. result.message = message;
  600. return result;
  601. },
  602. validate: function ($this, value, validator) {
  603. if (validator.lastValue === value && validator.lastFinished) {
  604. return !validator.lastValid;
  605. }
  606. if (validator.lastFinished === true) {
  607. validator.lastValue = value;
  608. validator.lastValid = true;
  609. validator.lastFinished = false;
  610. var rrjqbvValidator = validator;
  611. var rrjqbvThis = $this;
  612. executeFunctionByName(
  613. validator.callback,
  614. window,
  615. $this,
  616. value,
  617. function (data) {
  618. if (rrjqbvValidator.lastValue === data.value) {
  619. rrjqbvValidator.lastValid = data.valid;
  620. if (data.message) {
  621. rrjqbvValidator.message = data.message;
  622. }
  623. rrjqbvValidator.lastFinished = true;
  624. rrjqbvThis.data(
  625. "validation" + rrjqbvValidator.validatorName + "Message",
  626. rrjqbvValidator.message
  627. );
  628. // Timeout is set to avoid problems with the events being considered 'already fired'
  629. setTimeout(function () {
  630. if (!$this.is(":focus") && $this.parents("form").first().data("jqbvIsSubmitting")) {
  631. rrjqbvThis.trigger("blur.validation");
  632. } else {
  633. rrjqbvThis.trigger("revalidate.validation");
  634. }
  635. }, 1); // doesn't need a long timeout, just long enough for the event bubble to burst
  636. }
  637. }
  638. );
  639. }
  640. return false;
  641. }
  642. },
  643. ajax: {
  644. name: "ajax",
  645. init: function ($this, name) {
  646. return {
  647. validatorName: name,
  648. url: $this.data("validation" + name + "Ajax"),
  649. lastValue: $this.val(),
  650. lastValid: true,
  651. lastFinished: true
  652. };
  653. },
  654. validate: function ($this, value, validator) {
  655. if ("" + validator.lastValue === "" + value && validator.lastFinished === true) {
  656. return validator.lastValid === false;
  657. }
  658. if (validator.lastFinished === true) {
  659. validator.lastValue = value;
  660. validator.lastValid = true;
  661. validator.lastFinished = false;
  662. $.ajax({
  663. url: validator.url,
  664. data: "value=" + encodeURIComponent(value) + "&field=" + $this.attr("name"),
  665. dataType: "json",
  666. success : function (data) {
  667. if ("" + validator.lastValue === "" + data.value) {
  668. validator.lastValid = !!(data.valid);
  669. if (data.message) {
  670. validator.message = data.message;
  671. }
  672. validator.lastFinished = true;
  673. $this.data("validation" + validator.validatorName + "Message", validator.message);
  674. // Timeout is set to avoid problems with the events being considered 'already fired'
  675. setTimeout(function () {
  676. $this.trigger("revalidate.validation");
  677. }, 1); // doesn't need a long timeout, just long enough for the event bubble to burst
  678. }
  679. },
  680. failure: function () {
  681. validator.lastValid = true;
  682. validator.message = "ajax call failed";
  683. validator.lastFinished = true;
  684. $this.data("validation" + validator.validatorName + "Message", validator.message);
  685. // Timeout is set to avoid problems with the events being considered 'already fired'
  686. setTimeout(function () {
  687. $this.trigger("revalidate.validation");
  688. }, 1); // doesn't need a long timeout, just long enough for the event bubble to burst
  689. }
  690. });
  691. }
  692. return false;
  693. }
  694. },
  695. regex: {
  696. name: "regex",
  697. init: function ($this, name) {
  698. var result = {};
  699. var regexString = $this.data("validation" + name + "Regex");
  700. result.regex = regexFromString(regexString);
  701. if (regexString === undefined) {
  702. $.error("Can't find regex for '" + name + "' validator on '" + $this.attr("name") + "'");
  703. }
  704. var message = "Not in the expected format";
  705. if ($this.data("validation" + name + "Message")) {
  706. message = $this.data("validation" + name + "Message");
  707. }
  708. result.message = message;
  709. result.originalName = name;
  710. return result;
  711. },
  712. validate: function ($this, value, validator) {
  713. return (!validator.regex.test(value) && !validator.negative) ||
  714. (validator.regex.test(value) && validator.negative);
  715. }
  716. },
  717. email: {
  718. name: "email",
  719. init: function ($this, name) {
  720. var result = {};
  721. result.regex = regexFromString('[a-zA-Z0-9.!#$%&\u2019*+/=?^_`{|}~-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}');
  722. var message = "Not a valid email address";
  723. if ($this.data("validation" + name + "Message")) {
  724. message = $this.data("validation" + name + "Message");
  725. }
  726. result.message = message;
  727. result.originalName = name;
  728. return result;
  729. },
  730. validate: function ($this, value, validator) {
  731. return (!validator.regex.test(value) && !validator.negative) ||
  732. (validator.regex.test(value) && validator.negative);
  733. }
  734. },
  735. required: {
  736. name: "required",
  737. init: function ($this, name) {
  738. var message = "This is required";
  739. if ($this.data("validation" + name + "Message")) {
  740. message = $this.data("validation" + name + "Message");
  741. }
  742. return {message: message, includeEmpty: true};
  743. },
  744. validate: function ($this, value, validator) {
  745. return !!(
  746. (value.length === 0 && !validator.negative) ||
  747. (value.length > 0 && validator.negative)
  748. );
  749. },
  750. blockSubmit: true
  751. },
  752. match: {
  753. name: "match",
  754. init: function ($this, name) {
  755. var elementName = $this.data("validation" + name + "Match");
  756. var $form = $this.parents("form").first();
  757. var $element = $form.find("[name=\"" + elementName + "\"]").first();
  758. $element.bind("validation.validation", function () {
  759. $this.trigger("revalidate.validation", {submitting: true});
  760. });
  761. var result = {};
  762. result.element = $element;
  763. if ($element.length === 0) {
  764. $.error("Can't find field '" + elementName + "' to match '" + $this.attr("name") + "' against in '" + name + "' validator");
  765. }
  766. var message = "Must match";
  767. var $label = null;
  768. if (($label = $form.find("label[for=\"" + elementName + "\"]")).length) {
  769. message += " '" + $label.text() + "'";
  770. } else if (($label = $element.parents(".form-group").first().find("label")).length) {
  771. message += " '" + $label.first().text() + "'";
  772. }
  773. if ($this.data("validation" + name + "Message")) {
  774. message = $this.data("validation" + name + "Message");
  775. }
  776. result.message = message;
  777. return result;
  778. },
  779. validate: function ($this, value, validator) {
  780. return (value !== validator.element.val() && !validator.negative) ||
  781. (value === validator.element.val() && validator.negative);
  782. },
  783. blockSubmit: true,
  784. includeEmpty: true
  785. },
  786. max: {
  787. name: "max",
  788. init: function ($this, name) {
  789. var result = {};
  790. result.max = $this.data("validation" + name + "Max");
  791. result.message = "Too high: Maximum of '" + result.max + "'";
  792. if ($this.data("validation" + name + "Message")) {
  793. result.message = $this.data("validation" + name + "Message");
  794. }
  795. return result;
  796. },
  797. validate: function ($this, value, validator) {
  798. return (parseFloat(value, 10) > parseFloat(validator.max, 10) && !validator.negative) ||
  799. (parseFloat(value, 10) <= parseFloat(validator.max, 10) && validator.negative);
  800. }
  801. },
  802. min: {
  803. name: "min",
  804. init: function ($this, name) {
  805. var result = {};
  806. result.min = $this.data("validation" + name + "Min");
  807. result.message = "Too low: Minimum of '" + result.min + "'";
  808. if ($this.data("validation" + name + "Message")) {
  809. result.message = $this.data("validation" + name + "Message");
  810. }
  811. return result;
  812. },
  813. validate: function ($this, value, validator) {
  814. return (parseFloat(value) < parseFloat(validator.min) && !validator.negative) ||
  815. (parseFloat(value) >= parseFloat(validator.min) && validator.negative);
  816. }
  817. },
  818. maxlength: {
  819. name: "maxlength",
  820. init: function ($this, name) {
  821. var result = {};
  822. result.maxlength = $this.data("validation" + name + "Maxlength");
  823. result.message = "Too long: Maximum of '" + result.maxlength + "' characters";
  824. if ($this.data("validation" + name + "Message")) {
  825. result.message = $this.data("validation" + name + "Message");
  826. }
  827. return result;
  828. },
  829. validate: function ($this, value, validator) {
  830. return ((value.length > validator.maxlength) && !validator.negative) ||
  831. ((value.length <= validator.maxlength) && validator.negative);
  832. }
  833. },
  834. minlength: {
  835. name: "minlength",
  836. init: function ($this, name) {
  837. var result = {};
  838. result.minlength = $this.data("validation" + name + "Minlength");
  839. result.message = "Too short: Minimum of '" + result.minlength + "' characters";
  840. if ($this.data("validation" + name + "Message")) {
  841. result.message = $this.data("validation" + name + "Message");
  842. }
  843. return result;
  844. },
  845. validate: function ($this, value, validator) {
  846. return ((value.length < validator.minlength) && !validator.negative) ||
  847. ((value.length >= validator.minlength) && validator.negative);
  848. }
  849. },
  850. maxchecked: {
  851. name: "maxchecked",
  852. init: function ($this, name) {
  853. var result = {};
  854. var elements = $this.parents("form").first().find("[name=\"" + $this.attr("name") + "\"]");
  855. elements.bind("change.validation click.validation", function () {
  856. $this.trigger("revalidate.validation", {includeEmpty: true});
  857. });
  858. result.elements = elements;
  859. result.maxchecked = $this.data("validation" + name + "Maxchecked");
  860. var message = "Too many: Max '" + result.maxchecked + "' checked";
  861. if ($this.data("validation" + name + "Message")) {
  862. message = $this.data("validation" + name + "Message");
  863. }
  864. result.message = message;
  865. return result;
  866. },
  867. validate: function ($this, value, validator) {
  868. return (validator.elements.filter(":checked").length > validator.maxchecked && !validator.negative) ||
  869. (validator.elements.filter(":checked").length <= validator.maxchecked && validator.negative);
  870. },
  871. blockSubmit: true
  872. },
  873. minchecked: {
  874. name: "minchecked",
  875. init: function ($this, name) {
  876. var result = {};
  877. var elements = $this.parents("form").first().find("[name=\"" + $this.attr("name") + "\"]");
  878. elements.bind("change.validation click.validation", function () {
  879. $this.trigger("revalidate.validation", {includeEmpty: true});
  880. });
  881. result.elements = elements;
  882. result.minchecked = $this.data("validation" + name + "Minchecked");
  883. var message = "Too few: Min '" + result.minchecked + "' checked";
  884. if ($this.data("validation" + name + "Message")) {
  885. message = $this.data("validation" + name + "Message");
  886. }
  887. result.message = message;
  888. return result;
  889. },
  890. validate: function ($this, value, validator) {
  891. return (validator.elements.filter(":checked").length < validator.minchecked && !validator.negative) ||
  892. (validator.elements.filter(":checked").length >= validator.minchecked && validator.negative);
  893. },
  894. blockSubmit: true,
  895. includeEmpty: true
  896. },
  897. number: {
  898. name: "number",
  899. init: function ($this, name) {
  900. var result = {};
  901. result.step = 1;
  902. if ($this.attr("step")) {
  903. result.step = $this.attr("step");
  904. }
  905. if ($this.data("validation" + name + "Step")) {
  906. result.step = $this.data("validation" + name + "Step");
  907. }
  908. result.decimal = ".";
  909. if ($this.data("validation" + name + "Decimal")) {
  910. result.decimal = $this.data("validation" + name + "Decimal");
  911. }
  912. result.thousands = "";
  913. if ($this.data("validation" + name + "Thousands")) {
  914. result.thousands = $this.data("validation" + name + "Thousands");
  915. }
  916. result.regex = regexFromString("([+-]?\\d+(\\" + result.decimal + "\\d+)?)?");
  917. result.message = "Must be a number";
  918. var dataMessage = $this.data("validation" + name + "Message");
  919. if (dataMessage) {
  920. result.message = dataMessage;
  921. }
  922. return result;
  923. },
  924. validate: function ($this, value, validator) {
  925. var globalValue = value.replace(validator.decimal, ".").replace(validator.thousands, "");
  926. var multipliedValue = parseFloat(globalValue);
  927. var multipliedStep = parseFloat(validator.step);
  928. while (multipliedStep % 1 !== 0) {
  929. /* thanks to @jkey #57 */
  930. multipliedStep = parseFloat(multipliedStep.toPrecision(12)) * 10;
  931. multipliedValue = parseFloat(multipliedValue.toPrecision(12)) * 10;
  932. }
  933. var regexResult = validator.regex.test(value);
  934. var stepResult = parseFloat(multipliedValue) % parseFloat(multipliedStep) === 0;
  935. var typeResult = !isNaN(parseFloat(globalValue)) && isFinite(globalValue);
  936. var result = !(regexResult && stepResult && typeResult);
  937. return result;
  938. },
  939. message: "Must be a number"
  940. }
  941. },
  942. builtInValidators: {
  943. email: {
  944. name: "Email",
  945. type: "email"
  946. },
  947. passwordagain: {
  948. name: "Passwordagain",
  949. type: "match",
  950. match: "password",
  951. message: "Does not match the given password<!-- data-validator-paswordagain-message to override -->"
  952. },
  953. positive: {
  954. name: "Positive",
  955. type: "shortcut",
  956. shortcut: "number,positivenumber"
  957. },
  958. negative: {
  959. name: "Negative",
  960. type: "shortcut",
  961. shortcut: "number,negativenumber"
  962. },
  963. integer: {
  964. name: "Integer",
  965. type: "regex",
  966. regex: "[+-]?\\d+",
  967. message: "No decimal places allowed<!-- data-validator-integer-message to override -->"
  968. },
  969. positivenumber: {
  970. name: "Positivenumber",
  971. type: "min",
  972. min: 0,
  973. message: "Must be a positive number<!-- data-validator-positivenumber-message to override -->"
  974. },
  975. negativenumber: {
  976. name: "Negativenumber",
  977. type: "max",
  978. max: 0,
  979. message: "Must be a negative number<!-- data-validator-negativenumber-message to override -->"
  980. },
  981. required: {
  982. name: "Required",
  983. type: "required",
  984. message: "This is required<!-- data-validator-required-message to override -->"
  985. },
  986. checkone: {
  987. name: "Checkone",
  988. type: "minchecked",
  989. minchecked: 1,
  990. message: "Check at least one option<!-- data-validation-checkone-message to override -->"
  991. },
  992. number: {
  993. name: "Number",
  994. type: "number",
  995. decimal: ".",
  996. step: "1"
  997. },
  998. pattern: {
  999. name: "Pattern",
  1000. type: "regex",
  1001. message: "Not in expected format"
  1002. }
  1003. }
  1004. };
  1005. var formatValidatorName = function (name) {
  1006. return name
  1007. .toLowerCase()
  1008. .replace(
  1009. /(^|\s)([a-z])/g,
  1010. function (m, p1, p2) {
  1011. return p1 + p2.toUpperCase();
  1012. }
  1013. )
  1014. ;
  1015. };
  1016. var getValue = function ($this) {
  1017. // Extract the value we're talking about
  1018. var value = null;
  1019. var type = $this.attr("type");
  1020. if (type === "checkbox") {
  1021. value = ($this.is(":checked") ? value : "");
  1022. var checkboxParent = $this.parents("form").first() || $this.parents(".form-group").first();
  1023. if (checkboxParent) {
  1024. value = checkboxParent.find("input[name='" + $this.attr("name") + "']:checked").map(function (i, el) {
  1025. return $(el).val();
  1026. }).toArray().join(",");
  1027. }
  1028. }
  1029. else if (type === "radio") {
  1030. value = ($('input[name="' + $this.attr("name") + '"]:checked').length > 0 ? $this.val() : "");
  1031. var radioParent = $this.parents("form").first() || $this.parents(".form-group").first();
  1032. if (radioParent) {
  1033. value = radioParent.find("input[name='" + $this.attr("name") + "']:checked").map(function (i, el) {
  1034. return $(el).val();
  1035. }).toArray().join(",");
  1036. }
  1037. } else if (type === "number") {
  1038. if ($this[0].validity.valid) {
  1039. value = $this.val();
  1040. } else {
  1041. if ($this[0].validity.badInput || $this[0].validity.stepMismatch) {
  1042. value = "NaN";
  1043. } else {
  1044. value = "";
  1045. }
  1046. }
  1047. } else {
  1048. value = $this.val();
  1049. }
  1050. return value;
  1051. };
  1052. function regexFromString(inputstring) {
  1053. return new RegExp("^" + inputstring + "$");
  1054. }
  1055. /**
  1056. * Thanks to Jason Bunting / Alex Nazarov via StackOverflow.com
  1057. *
  1058. * http://stackoverflow.com/a/4351575
  1059. **/
  1060. function executeFunctionByName(functionName, context /*, args */) {
  1061. var args = Array.prototype.slice.call(arguments, 2);
  1062. var namespaces = functionName.split(".");
  1063. var func = namespaces.pop();
  1064. for (var i = 0; i < namespaces.length; i++) {
  1065. context = context[namespaces[i]];
  1066. }
  1067. return context[func].apply(context, args);
  1068. }
  1069. $.fn.jqBootstrapValidation = function (method) {
  1070. if (defaults.methods[method]) {
  1071. return defaults.methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
  1072. } else if (typeof method === 'object' || !method) {
  1073. return defaults.methods.init.apply(this, arguments);
  1074. } else {
  1075. $.error('Method ' + method + ' does not exist on jQuery.jqBootstrapValidation');
  1076. return null;
  1077. }
  1078. };
  1079. $.jqBootstrapValidation = function (options) {
  1080. $(":input").not("[type=image],[type=submit]").jqBootstrapValidation.apply(this, arguments);
  1081. };
  1082. })(jQuery);