You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1243 lines
39 KiB

9 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
9 years ago
10 years ago
9 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
  1. /*!
  2. * # Semantic UI 2.0.0 - Form Validation
  3. * http://github.com/semantic-org/semantic-ui/
  4. *
  5. *
  6. * Copyright 2014 Contributors
  7. * Released under the MIT license
  8. * http://opensource.org/licenses/MIT
  9. *
  10. */
  11. ;(function ( $, window, document, undefined ) {
  12. "use strict";
  13. $.fn.form = function(parameters) {
  14. var
  15. $allModules = $(this),
  16. moduleSelector = $allModules.selector || '',
  17. time = new Date().getTime(),
  18. performance = [],
  19. query = arguments[0],
  20. legacyParameters = arguments[1],
  21. methodInvoked = (typeof query == 'string'),
  22. queryArguments = [].slice.call(arguments, 1),
  23. returnedValue
  24. ;
  25. $allModules
  26. .each(function() {
  27. var
  28. $module = $(this),
  29. element = this,
  30. formErrors = [],
  31. keyHeldDown = false,
  32. // set at run-time
  33. $field,
  34. $group,
  35. $message,
  36. $prompt,
  37. $submit,
  38. $clear,
  39. $reset,
  40. settings,
  41. validation,
  42. metadata,
  43. selector,
  44. className,
  45. error,
  46. namespace,
  47. moduleNamespace,
  48. eventNamespace,
  49. instance,
  50. module
  51. ;
  52. module = {
  53. initialize: function() {
  54. // settings grabbed at run time
  55. module.get.settings();
  56. if(methodInvoked) {
  57. if(instance === undefined) {
  58. module.instantiate();
  59. }
  60. module.invoke(query);
  61. }
  62. else {
  63. module.verbose('Initializing form validation', $module, settings);
  64. module.bindEvents();
  65. module.set.defaults();
  66. module.instantiate();
  67. }
  68. },
  69. instantiate: function() {
  70. module.verbose('Storing instance of module', module);
  71. instance = module;
  72. $module
  73. .data(moduleNamespace, module)
  74. ;
  75. },
  76. destroy: function() {
  77. module.verbose('Destroying previous module', instance);
  78. module.removeEvents();
  79. $module
  80. .removeData(moduleNamespace)
  81. ;
  82. },
  83. refresh: function() {
  84. module.verbose('Refreshing selector cache');
  85. $field = $module.find(selector.field);
  86. $group = $module.find(selector.group);
  87. $message = $module.find(selector.message);
  88. $prompt = $module.find(selector.prompt);
  89. $submit = $module.find(selector.submit);
  90. $clear = $module.find(selector.clear);
  91. $reset = $module.find(selector.reset);
  92. },
  93. submit: function() {
  94. module.verbose('Submitting form', $module);
  95. $module
  96. .submit()
  97. ;
  98. },
  99. attachEvents: function(selector, action) {
  100. action = action || 'submit';
  101. $(selector)
  102. .on('click' + eventNamespace, function(event) {
  103. module[action]();
  104. event.preventDefault();
  105. })
  106. ;
  107. },
  108. bindEvents: function() {
  109. module.verbose('Attaching form events');
  110. $module
  111. .on('submit' + eventNamespace, module.validate.form)
  112. .on('blur' + eventNamespace, selector.field, module.event.field.blur)
  113. .on('click' + eventNamespace, selector.submit, module.submit)
  114. .on('click' + eventNamespace, selector.reset, module.reset)
  115. .on('click' + eventNamespace, selector.clear, module.clear)
  116. ;
  117. if(settings.keyboardShortcuts) {
  118. $module
  119. .on('keydown' + eventNamespace, selector.field, module.event.field.keydown)
  120. ;
  121. }
  122. $field
  123. .each(function() {
  124. var
  125. $input = $(this),
  126. type = $input.prop('type'),
  127. inputEvent = module.get.changeEvent(type, $input)
  128. ;
  129. $(this)
  130. .on(inputEvent + eventNamespace, module.event.field.change)
  131. ;
  132. })
  133. ;
  134. },
  135. clear: function() {
  136. $field
  137. .each(function () {
  138. var
  139. $field = $(this),
  140. $element = $field.parent(),
  141. $fieldGroup = $field.closest($group),
  142. $prompt = $fieldGroup.find(selector.prompt),
  143. defaultValue = $field.data(metadata.defaultValue) || '',
  144. isCheckbox = $element.is(selector.uiCheckbox),
  145. isDropdown = $element.is(selector.uiDropdown),
  146. isErrored = $fieldGroup.hasClass(className.error)
  147. ;
  148. if(isErrored) {
  149. module.verbose('Resetting error on field', $fieldGroup);
  150. $fieldGroup.removeClass(className.error);
  151. $prompt.remove();
  152. }
  153. if(isDropdown) {
  154. module.verbose('Resetting dropdown value', $element, defaultValue);
  155. $element.dropdown('clear');
  156. }
  157. else if(isCheckbox) {
  158. $element.checkbox('uncheck');
  159. }
  160. else {
  161. module.verbose('Resetting field value', $field, defaultValue);
  162. $field.val('');
  163. }
  164. })
  165. ;
  166. },
  167. reset: function() {
  168. $field
  169. .each(function () {
  170. var
  171. $field = $(this),
  172. $element = $field.parent(),
  173. $fieldGroup = $field.closest($group),
  174. $prompt = $fieldGroup.find(selector.prompt),
  175. defaultValue = $field.data(metadata.defaultValue) || '',
  176. isCheckbox = $element.is(selector.uiCheckbox),
  177. isDropdown = $element.is(selector.uiDropdown),
  178. isErrored = $fieldGroup.hasClass(className.error)
  179. ;
  180. if(isErrored) {
  181. module.verbose('Resetting error on field', $fieldGroup);
  182. $fieldGroup.removeClass(className.error);
  183. $prompt.remove();
  184. }
  185. if(isDropdown) {
  186. module.verbose('Resetting dropdown value', $element, defaultValue);
  187. $element.dropdown('restore defaults');
  188. }
  189. else if(isCheckbox) {
  190. module.verbose('Resetting checkbox value', $element, defaultValue);
  191. if(defaultValue === true) {
  192. $element.checkbox('check');
  193. }
  194. else {
  195. $element.checkbox('uncheck');
  196. }
  197. }
  198. else {
  199. module.verbose('Resetting field value', $field, defaultValue);
  200. $field.val(defaultValue);
  201. }
  202. })
  203. ;
  204. },
  205. removeEvents: function() {
  206. $module
  207. .off(eventNamespace)
  208. ;
  209. $field
  210. .off(eventNamespace)
  211. ;
  212. $submit
  213. .off(eventNamespace)
  214. ;
  215. $field
  216. .off(eventNamespace)
  217. ;
  218. },
  219. event: {
  220. field: {
  221. keydown: function(event) {
  222. var
  223. $field = $(this),
  224. key = event.which,
  225. keyCode = {
  226. enter : 13,
  227. escape : 27
  228. }
  229. ;
  230. if( key == keyCode.escape) {
  231. module.verbose('Escape key pressed blurring field');
  232. $field
  233. .blur()
  234. ;
  235. }
  236. if(!event.ctrlKey && key == keyCode.enter && $field.is(selector.input) && $field.not(selector.checkbox).length > 0 ) {
  237. $submit
  238. .addClass(className.pressed)
  239. ;
  240. if(!keyHeldDown) {
  241. $field
  242. .one('keyup' + eventNamespace, module.event.field.keyup)
  243. ;
  244. module.submit();
  245. module.debug('Enter pressed on input submitting form');
  246. }
  247. keyHeldDown = true;
  248. }
  249. },
  250. keyup: function() {
  251. keyHeldDown = false;
  252. $submit.removeClass(className.pressed);
  253. },
  254. blur: function() {
  255. var
  256. $field = $(this),
  257. $fieldGroup = $field.closest($group)
  258. ;
  259. if( $fieldGroup.hasClass(className.error) ) {
  260. module.debug('Revalidating field', $field, module.get.validation($field));
  261. module.validate.field( module.get.validation($field) );
  262. }
  263. else if(settings.on == 'blur' || settings.on == 'change') {
  264. module.validate.field( module.get.validation($field) );
  265. }
  266. },
  267. change: function() {
  268. var
  269. $field = $(this),
  270. $fieldGroup = $field.closest($group)
  271. ;
  272. if(settings.on == 'change' || ( $fieldGroup.hasClass(className.error) && settings.revalidate) ) {
  273. clearTimeout(module.timer);
  274. module.timer = setTimeout(function() {
  275. module.debug('Revalidating field', $field, module.get.validation($field));
  276. module.validate.field( module.get.validation($field) );
  277. }, settings.delay);
  278. }
  279. }
  280. }
  281. },
  282. get: {
  283. changeEvent: function(type, $input) {
  284. if(type == 'checkbox' || type == 'radio' || type == 'hidden' || $input.is('select')) {
  285. return 'change';
  286. }
  287. else {
  288. return module.get.inputEvent();
  289. }
  290. },
  291. inputEvent: function() {
  292. return (document.createElement('input').oninput !== undefined)
  293. ? 'input'
  294. : (document.createElement('input').onpropertychange !== undefined)
  295. ? 'propertychange'
  296. : 'keyup'
  297. ;
  298. },
  299. settings: function() {
  300. var
  301. firstProperty
  302. ;
  303. if($.isPlainObject(parameters)) {
  304. var
  305. keys = Object.keys(parameters),
  306. isLegacySettings = (keys.length > 0)
  307. ? (parameters[keys[0]].identifier !== undefined)
  308. : false
  309. ;
  310. if(isLegacySettings) {
  311. // 1.x (ducktyped)
  312. settings = $.extend(true, {}, $.fn.form.settings, legacyParameters);
  313. validation = $.extend({}, $.fn.form.settings.defaults, parameters);
  314. module.error(settings.error.oldSyntax, element);
  315. module.verbose('Extending settings from legacy parameters', validation, settings);
  316. }
  317. else {
  318. // 2.x
  319. settings = $.extend(true, {}, $.fn.form.settings, parameters);
  320. validation = $.extend({}, $.fn.form.settings.defaults, settings.fields);
  321. module.verbose('Extending settings', validation, settings);
  322. }
  323. }
  324. else {
  325. settings = $.fn.form.settings;
  326. validation = $.fn.form.settings.defaults;
  327. module.verbose('Using default form validation', validation, settings);
  328. }
  329. // shorthand
  330. namespace = settings.namespace;
  331. metadata = settings.metadata;
  332. selector = settings.selector;
  333. className = settings.className;
  334. error = settings.error;
  335. moduleNamespace = 'module-' + namespace;
  336. eventNamespace = '.' + namespace;
  337. // grab instance
  338. instance = $module.data(moduleNamespace);
  339. // refresh selector cache
  340. module.refresh();
  341. },
  342. field: function(identifier) {
  343. module.verbose('Finding field with identifier', identifier);
  344. if( $field.filter('#' + identifier).length > 0 ) {
  345. return $field.filter('#' + identifier);
  346. }
  347. else if( $field.filter('[name="' + identifier +'"]').length > 0 ) {
  348. return $field.filter('[name="' + identifier +'"]');
  349. }
  350. else if( $field.filter('[name="' + identifier +'[]"]').length > 0 ) {
  351. return $field.filter('[name="' + identifier +'[]"]');
  352. }
  353. else if( $field.filter('[data-' + metadata.validate + '="'+ identifier +'"]').length > 0 ) {
  354. return $field.filter('[data-' + metadata.validate + '="'+ identifier +'"]');
  355. }
  356. return $('<input/>');
  357. },
  358. fields: function(fields) {
  359. var
  360. $fields = $()
  361. ;
  362. $.each(fields, function(index, name) {
  363. $fields = $fields.add( module.get.field(name) );
  364. });
  365. return $fields;
  366. },
  367. validation: function($field) {
  368. var
  369. rules
  370. ;
  371. $.each(validation, function(fieldName, field) {
  372. if( module.get.field(field.identifier).get(0) == $field.get(0) ) {
  373. rules = field;
  374. }
  375. });
  376. return rules || false;
  377. },
  378. value: function (field) {
  379. var
  380. fields = [],
  381. results
  382. ;
  383. fields.push(field);
  384. results = module.get.values.call(element, fields);
  385. return results[field];
  386. },
  387. values: function (fields) {
  388. var
  389. $fields = $.isArray(fields)
  390. ? module.get.fields(fields)
  391. : $field,
  392. values = {}
  393. ;
  394. $fields.each(function(index, field) {
  395. var
  396. $field = $(field),
  397. type = $field.prop('type'),
  398. name = $field.prop('name'),
  399. value = $field.val(),
  400. isCheckbox = $field.is(selector.checkbox),
  401. isRadio = $field.is(selector.radio),
  402. isMultiple = (name.indexOf('[]') !== -1),
  403. isChecked = (isCheckbox)
  404. ? $field.is(':checked')
  405. : false
  406. ;
  407. if(name) {
  408. if(isMultiple) {
  409. name = name.replace('[]', '');
  410. if(!values[name]) {
  411. values[name] = [];
  412. }
  413. if(isCheckbox) {
  414. if(isChecked) {
  415. values[name].push(value);
  416. }
  417. else {
  418. module.debug('Omitted unchecked checkbox', $field);
  419. return true;
  420. }
  421. }
  422. else {
  423. values[name].push(value);
  424. }
  425. }
  426. else {
  427. if(isRadio) {
  428. if(isChecked) {
  429. values[name] = value;
  430. }
  431. }
  432. else if(isCheckbox) {
  433. if(isChecked) {
  434. values[name] = true;
  435. }
  436. else {
  437. module.debug('Omitted unchecked checkbox', $field);
  438. return true;
  439. }
  440. }
  441. else {
  442. values[name] = value;
  443. }
  444. }
  445. }
  446. });
  447. return values;
  448. }
  449. },
  450. has: {
  451. field: function(identifier) {
  452. module.verbose('Checking for existence of a field with identifier', identifier);
  453. if( $field.filter('#' + identifier).length > 0 ) {
  454. return true;
  455. }
  456. else if( $field.filter('[name="' + identifier +'"]').length > 0 ) {
  457. return true;
  458. }
  459. else if( $field.filter('[data-' + metadata.validate + '="'+ identifier +'"]').length > 0 ) {
  460. return true;
  461. }
  462. return false;
  463. }
  464. },
  465. add: {
  466. prompt: function(identifier, errors) {
  467. var
  468. $field = module.get.field(identifier),
  469. $fieldGroup = $field.closest($group),
  470. $prompt = $fieldGroup.children(selector.prompt),
  471. promptExists = ($prompt.length !== 0)
  472. ;
  473. errors = (typeof errors == 'string')
  474. ? [errors]
  475. : errors
  476. ;
  477. module.verbose('Adding field error state', identifier);
  478. $fieldGroup
  479. .addClass(className.error)
  480. ;
  481. if(settings.inline) {
  482. if(!promptExists) {
  483. $prompt = settings.templates.prompt(errors);
  484. $prompt
  485. .appendTo($fieldGroup)
  486. ;
  487. }
  488. $prompt
  489. .html(errors[0])
  490. ;
  491. if(!promptExists) {
  492. if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) {
  493. module.verbose('Displaying error with css transition', settings.transition);
  494. $prompt.transition(settings.transition + ' in', settings.duration);
  495. }
  496. else {
  497. module.verbose('Displaying error with fallback javascript animation');
  498. $prompt
  499. .fadeIn(settings.duration)
  500. ;
  501. }
  502. }
  503. else {
  504. module.verbose('Inline errors are disabled, no inline error added', identifier);
  505. }
  506. }
  507. },
  508. errors: function(errors) {
  509. module.debug('Adding form error messages', errors);
  510. $message
  511. .html( settings.templates.error(errors) )
  512. ;
  513. }
  514. },
  515. remove: {
  516. prompt: function(field) {
  517. var
  518. $field = module.get.field(field.identifier),
  519. $fieldGroup = $field.closest($group),
  520. $prompt = $fieldGroup.children(selector.prompt)
  521. ;
  522. $fieldGroup
  523. .removeClass(className.error)
  524. ;
  525. if(settings.inline && $prompt.is(':visible')) {
  526. module.verbose('Removing prompt for field', field);
  527. if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) {
  528. $prompt.transition(settings.transition + ' out', settings.duration, function() {
  529. $prompt.remove();
  530. });
  531. }
  532. else {
  533. $prompt
  534. .fadeOut(settings.duration, function(){
  535. $prompt.remove();
  536. })
  537. ;
  538. }
  539. }
  540. }
  541. },
  542. set: {
  543. success: function() {
  544. $module
  545. .removeClass(className.error)
  546. .addClass(className.success)
  547. ;
  548. },
  549. defaults: function () {
  550. $field
  551. .each(function () {
  552. var
  553. $field = $(this),
  554. isCheckbox = ($field.filter(selector.checkbox).length > 0),
  555. value = (isCheckbox)
  556. ? $field.is(':checked')
  557. : $field.val()
  558. ;
  559. $field.data(metadata.defaultValue, value);
  560. })
  561. ;
  562. },
  563. error: function() {
  564. $module
  565. .removeClass(className.success)
  566. .addClass(className.error)
  567. ;
  568. },
  569. value: function (field, value) {
  570. var
  571. fields = {}
  572. ;
  573. fields[field] = value;
  574. return module.set.values.call(element, fields);
  575. },
  576. values: function (fields) {
  577. if($.isEmptyObject(fields)) {
  578. return;
  579. }
  580. $.each(fields, function(key, value) {
  581. var
  582. $field = module.get.field(key),
  583. $element = $field.parent(),
  584. isMultiple = $.isArray(value),
  585. isCheckbox = $element.is(selector.uiCheckbox),
  586. isDropdown = $element.is(selector.uiDropdown),
  587. isRadio = ($field.is(selector.radio) && isCheckbox),
  588. fieldExists = ($field.length > 0),
  589. $multipleField
  590. ;
  591. if(fieldExists) {
  592. if(isMultiple && isCheckbox) {
  593. module.verbose('Selecting multiple', value, $field);
  594. $element.checkbox('uncheck');
  595. $.each(value, function(index, value) {
  596. $multipleField = $field.filter('[value="' + value + '"]');
  597. $element = $multipleField.parent();
  598. if($multipleField.length > 0) {
  599. $element.checkbox('check');
  600. }
  601. });
  602. }
  603. else if(isRadio) {
  604. module.verbose('Selecting radio value', value, $field);
  605. $field.filter('[value="' + value + '"]')
  606. .parent(selector.uiCheckbox)
  607. .checkbox('check')
  608. ;
  609. }
  610. else if(isCheckbox) {
  611. module.verbose('Setting checkbox value', value, $element);
  612. if(value === true) {
  613. $element.checkbox('check');
  614. }
  615. else {
  616. $element.checkbox('uncheck');
  617. }
  618. }
  619. else if(isDropdown) {
  620. module.verbose('Setting dropdown value', value, $element);
  621. $element.dropdown('set selected', value);
  622. }
  623. else {
  624. module.verbose('Setting field value', value, $field);
  625. $field.val(value);
  626. }
  627. }
  628. });
  629. }
  630. },
  631. validate: {
  632. form: function(event) {
  633. var
  634. allValid = true,
  635. apiRequest
  636. ;
  637. // input keydown event will fire submit repeatedly by browser default
  638. if(keyHeldDown) {
  639. return false;
  640. }
  641. // reset errors
  642. formErrors = [];
  643. $.each(validation, function(fieldName, field) {
  644. if( !( module.validate.field(field) ) ) {
  645. allValid = false;
  646. }
  647. });
  648. if(allValid) {
  649. module.debug('Form has no validation errors, submitting');
  650. module.set.success();
  651. return settings.onSuccess.call(element, event);
  652. }
  653. else {
  654. module.debug('Form has errors');
  655. module.set.error();
  656. if(!settings.inline) {
  657. module.add.errors(formErrors);
  658. }
  659. // prevent ajax submit
  660. if($module.data('moduleApi') !== undefined) {
  661. event.stopImmediatePropagation();
  662. }
  663. return settings.onFailure.call(element, formErrors);
  664. }
  665. },
  666. // takes a validation object and returns whether field passes validation
  667. field: function(field) {
  668. var
  669. $field = module.get.field(field.identifier),
  670. fieldValid = true,
  671. fieldErrors = []
  672. ;
  673. if($field.prop('disabled')) {
  674. module.debug('Field is disabled. Skipping', field.identifier);
  675. fieldValid = true;
  676. }
  677. else if(field.optional && $.trim($field.val()) === ''){
  678. module.debug('Field is optional and empty. Skipping', field.identifier);
  679. fieldValid = true;
  680. }
  681. else if(field.rules !== undefined) {
  682. $.each(field.rules, function(index, rule) {
  683. if( module.has.field(field.identifier) && !( module.validate.rule(field, rule) ) ) {
  684. module.debug('Field is invalid', field.identifier, rule.type);
  685. fieldErrors.push(rule.prompt);
  686. fieldValid = false;
  687. }
  688. });
  689. }
  690. if(fieldValid) {
  691. module.remove.prompt(field, fieldErrors);
  692. settings.onValid.call($field);
  693. }
  694. else {
  695. formErrors = formErrors.concat(fieldErrors);
  696. module.add.prompt(field.identifier, fieldErrors);
  697. settings.onInvalid.call($field, fieldErrors);
  698. return false;
  699. }
  700. return true;
  701. },
  702. // takes validation rule and returns whether field passes rule
  703. rule: function(field, validation) {
  704. var
  705. $field = module.get.field(field.identifier),
  706. type = validation.type,
  707. value = $field.val(),
  708. bracket = type.match(settings.regExp.bracket),
  709. isValid = true,
  710. rule,
  711. ancillary,
  712. functionType
  713. ;
  714. // cast to string
  715. value = $.trim($field.val() + '');
  716. // if bracket notation is used, pass in extra parameters
  717. if(bracket) {
  718. ancillary = '' + bracket[1];
  719. functionType = type.replace(bracket[0], '');
  720. rule = settings.rules[functionType];
  721. if( !$.isFunction(rule) ) {
  722. module.error(error.noRule, functionType);
  723. return;
  724. }
  725. isValid = rule.call($field, value, ancillary);
  726. }
  727. else {
  728. rule = settings.rules[type];
  729. if( !$.isFunction(rule) ) {
  730. module.error(error.noRule, type);
  731. return;
  732. }
  733. isValid = rule.call($field, value);
  734. }
  735. return isValid;
  736. }
  737. },
  738. setting: function(name, value) {
  739. if( $.isPlainObject(name) ) {
  740. $.extend(true, settings, name);
  741. }
  742. else if(value !== undefined) {
  743. settings[name] = value;
  744. }
  745. else {
  746. return settings[name];
  747. }
  748. },
  749. internal: function(name, value) {
  750. if( $.isPlainObject(name) ) {
  751. $.extend(true, module, name);
  752. }
  753. else if(value !== undefined) {
  754. module[name] = value;
  755. }
  756. else {
  757. return module[name];
  758. }
  759. },
  760. debug: function() {
  761. if(settings.debug) {
  762. if(settings.performance) {
  763. module.performance.log(arguments);
  764. }
  765. else {
  766. module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
  767. module.debug.apply(console, arguments);
  768. }
  769. }
  770. },
  771. verbose: function() {
  772. if(settings.verbose && settings.debug) {
  773. if(settings.performance) {
  774. module.performance.log(arguments);
  775. }
  776. else {
  777. module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
  778. module.verbose.apply(console, arguments);
  779. }
  780. }
  781. },
  782. error: function() {
  783. module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
  784. module.error.apply(console, arguments);
  785. },
  786. performance: {
  787. log: function(message) {
  788. var
  789. currentTime,
  790. executionTime,
  791. previousTime
  792. ;
  793. if(settings.performance) {
  794. currentTime = new Date().getTime();
  795. previousTime = time || currentTime;
  796. executionTime = currentTime - previousTime;
  797. time = currentTime;
  798. performance.push({
  799. 'Name' : message[0],
  800. 'Arguments' : [].slice.call(message, 1) || '',
  801. 'Element' : element,
  802. 'Execution Time' : executionTime
  803. });
  804. }
  805. clearTimeout(module.performance.timer);
  806. module.performance.timer = setTimeout(module.performance.display, 500);
  807. },
  808. display: function() {
  809. var
  810. title = settings.name + ':',
  811. totalTime = 0
  812. ;
  813. time = false;
  814. clearTimeout(module.performance.timer);
  815. $.each(performance, function(index, data) {
  816. totalTime += data['Execution Time'];
  817. });
  818. title += ' ' + totalTime + 'ms';
  819. if(moduleSelector) {
  820. title += ' \'' + moduleSelector + '\'';
  821. }
  822. if($allModules.length > 1) {
  823. title += ' ' + '(' + $allModules.length + ')';
  824. }
  825. if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
  826. console.groupCollapsed(title);
  827. if(console.table) {
  828. console.table(performance);
  829. }
  830. else {
  831. $.each(performance, function(index, data) {
  832. console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
  833. });
  834. }
  835. console.groupEnd();
  836. }
  837. performance = [];
  838. }
  839. },
  840. invoke: function(query, passedArguments, context) {
  841. var
  842. object = instance,
  843. maxDepth,
  844. found,
  845. response
  846. ;
  847. passedArguments = passedArguments || queryArguments;
  848. context = element || context;
  849. if(typeof query == 'string' && object !== undefined) {
  850. query = query.split(/[\. ]/);
  851. maxDepth = query.length - 1;
  852. $.each(query, function(depth, value) {
  853. var camelCaseValue = (depth != maxDepth)
  854. ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
  855. : query
  856. ;
  857. if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
  858. object = object[camelCaseValue];
  859. }
  860. else if( object[camelCaseValue] !== undefined ) {
  861. found = object[camelCaseValue];
  862. return false;
  863. }
  864. else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
  865. object = object[value];
  866. }
  867. else if( object[value] !== undefined ) {
  868. found = object[value];
  869. return false;
  870. }
  871. else {
  872. return false;
  873. }
  874. });
  875. }
  876. if( $.isFunction( found ) ) {
  877. response = found.apply(context, passedArguments);
  878. }
  879. else if(found !== undefined) {
  880. response = found;
  881. }
  882. if($.isArray(returnedValue)) {
  883. returnedValue.push(response);
  884. }
  885. else if(returnedValue !== undefined) {
  886. returnedValue = [returnedValue, response];
  887. }
  888. else if(response !== undefined) {
  889. returnedValue = response;
  890. }
  891. return found;
  892. }
  893. };
  894. module.initialize();
  895. })
  896. ;
  897. return (returnedValue !== undefined)
  898. ? returnedValue
  899. : this
  900. ;
  901. };
  902. $.fn.form.settings = {
  903. name : 'Form',
  904. namespace : 'form',
  905. debug : false,
  906. verbose : false,
  907. performance : true,
  908. fields : false,
  909. keyboardShortcuts : true,
  910. on : 'submit',
  911. inline : false,
  912. delay : 200,
  913. revalidate : true,
  914. transition : 'scale',
  915. duration : 200,
  916. onValid : function() {},
  917. onInvalid : function() {},
  918. onSuccess : function() { return true; },
  919. onFailure : function() { return false; },
  920. metadata : {
  921. defaultValue : 'default',
  922. validate : 'validate'
  923. },
  924. regExp: {
  925. bracket : /\[(.*)\]/i,
  926. escape : /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,
  927. email : "[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?",
  928. integer : /^\-?\d+$/,
  929. flags : /^\/(.*)\/(.*)?/,
  930. url : /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/i
  931. },
  932. selector : {
  933. checkbox : 'input[type="checkbox"], input[type="radio"]',
  934. clear : '.clear',
  935. field : 'input, textarea, select',
  936. group : '.field',
  937. input : 'input',
  938. message : '.error.message',
  939. prompt : '.prompt.label',
  940. radio : 'input[type="radio"]',
  941. reset : '.reset:not([type="reset"])',
  942. submit : '.submit:not([type="submit"])',
  943. uiCheckbox : '.ui.checkbox',
  944. uiDropdown : '.ui.dropdown'
  945. },
  946. className : {
  947. error : 'error',
  948. label : 'ui prompt label',
  949. pressed : 'down',
  950. success : 'success'
  951. },
  952. error: {
  953. oldSyntax : 'Starting in 2.0 forms now only take a single settings object. Validation settings converted to new syntax automatically.',
  954. noRule : 'There is no rule matching the one you specified',
  955. method : 'The method you called is not defined.'
  956. },
  957. templates: {
  958. // template that produces error message
  959. error: function(errors) {
  960. var
  961. html = '<ul class="list">'
  962. ;
  963. $.each(errors, function(index, value) {
  964. html += '<li>' + value + '</li>';
  965. });
  966. html += '</ul>';
  967. return $(html);
  968. },
  969. // template that produces label
  970. prompt: function(errors) {
  971. return $('<div/>')
  972. .addClass('ui red pointing prompt label')
  973. .html(errors[0])
  974. ;
  975. }
  976. },
  977. rules: {
  978. // checkbox checked
  979. checked: function() {
  980. return ($(this).filter(':checked').length > 0);
  981. },
  982. // value contains text (insensitive)
  983. contains: function(value, text) {
  984. // escape regex characters
  985. text = text.replace($.fn.form.settings.regExp.escape, "\\$&");
  986. return (value.search( new RegExp(text, 'i') ) !== -1);
  987. },
  988. // value contains text (case sensitive)
  989. containsExactly: function(value, text) {
  990. // escape regex characters
  991. text = text.replace($.fn.form.settings.regExp.escape, "\\$&");
  992. return (value.search( new RegExp(text) ) !== -1);
  993. },
  994. // is most likely an email
  995. email: function(value){
  996. var
  997. emailRegExp = new RegExp($.fn.form.settings.regExp.email, 'i')
  998. ;
  999. return emailRegExp.test(value);
  1000. },
  1001. // is not empty or blank string
  1002. empty: function(value) {
  1003. return !(value === undefined || '' === value || $.isArray(value) && value.length === 0);
  1004. },
  1005. // is valid integer
  1006. integer: function(value, range) {
  1007. var
  1008. intRegExp = $.fn.form.settings.regExp.integer,
  1009. min,
  1010. max,
  1011. parts
  1012. ;
  1013. if(range === undefined || range === '' || range === '..') {
  1014. // do nothing
  1015. }
  1016. else if(range.indexOf('..') == -1) {
  1017. if(intRegExp.test(range)) {
  1018. min = max = range - 0;
  1019. }
  1020. }
  1021. else {
  1022. parts = range.split('..', 2);
  1023. if(intRegExp.test(parts[0])) {
  1024. min = parts[0] - 0;
  1025. }
  1026. if(intRegExp.test(parts[1])) {
  1027. max = parts[1] - 0;
  1028. }
  1029. }
  1030. return (
  1031. intRegExp.test(value) &&
  1032. (min === undefined || value >= min) &&
  1033. (max === undefined || value <= max)
  1034. );
  1035. },
  1036. // is value (case insensitive)
  1037. is: function(value, text) {
  1038. text = (typeof text == 'string')
  1039. ? text.toLowerCase()
  1040. : text
  1041. ;
  1042. value = (typeof value == 'string')
  1043. ? value.toLowerCase()
  1044. : value
  1045. ;
  1046. return (value == text);
  1047. },
  1048. // is value
  1049. isExactly: function(value, text) {
  1050. return (value == text);
  1051. },
  1052. // is at least string length
  1053. length: function(value, requiredLength) {
  1054. return (value !== undefined)
  1055. ? (value.length >= requiredLength)
  1056. : false
  1057. ;
  1058. },
  1059. // matches another field
  1060. different: function(value, fieldIdentifier) {
  1061. // use either id or name of field
  1062. var
  1063. $form = $(this),
  1064. matchingValue
  1065. ;
  1066. if( $('[data-validate="'+ fieldIdentifier +'"]').length > 0 ) {
  1067. matchingValue = $('[data-validate="'+ fieldIdentifier +'"]').val();
  1068. }
  1069. else if($('#' + fieldIdentifier).length > 0) {
  1070. matchingValue = $('#' + fieldIdentifier).val();
  1071. }
  1072. else if($('[name="' + fieldIdentifier +'"]').length > 0) {
  1073. matchingValue = $('[name="' + fieldIdentifier + '"]').val();
  1074. }
  1075. return (matchingValue !== undefined)
  1076. ? ( value.toString() !== matchingValue.toString() )
  1077. : false
  1078. ;
  1079. },
  1080. // matches another field
  1081. match: function(value, fieldIdentifier) {
  1082. // use either id or name of field
  1083. var
  1084. $form = $(this),
  1085. matchingValue
  1086. ;
  1087. if( $('[data-validate="'+ fieldIdentifier +'"]').length > 0 ) {
  1088. matchingValue = $('[data-validate="'+ fieldIdentifier +'"]').val();
  1089. }
  1090. else if($('#' + fieldIdentifier).length > 0) {
  1091. matchingValue = $('#' + fieldIdentifier).val();
  1092. }
  1093. else if($('[name="' + fieldIdentifier +'"]').length > 0) {
  1094. matchingValue = $('[name="' + fieldIdentifier + '"]').val();
  1095. }
  1096. return (matchingValue !== undefined)
  1097. ? ( value.toString() == matchingValue.toString() )
  1098. : false
  1099. ;
  1100. },
  1101. maxCount: function(value, count) {
  1102. value = value.split(',');
  1103. return ($.isArray(value) && value.length <= count);
  1104. },
  1105. exactCount: function(value, count) {
  1106. value = value.split(',');
  1107. return ($.isArray(value) && value.length == count);
  1108. },
  1109. minCount: function(value, count) {
  1110. value = value.split(',');
  1111. return ($.isArray(value) && value.length >= count);
  1112. },
  1113. regExp: function(value, regExp) {
  1114. var
  1115. regExpParts = regExp.match($.fn.form.settings.regExp.flags),
  1116. flags
  1117. ;
  1118. // regular expression specified as /baz/gi (flags)
  1119. if(regExpParts) {
  1120. regExp = (regExpParts.length >= 2)
  1121. ? regExpParts[1]
  1122. : regExp
  1123. ;
  1124. flags = (regExpParts.length >= 3)
  1125. ? regExpParts[2]
  1126. : ''
  1127. ;
  1128. }
  1129. return value.match( new RegExp(regExp, flags) );
  1130. },
  1131. // string length is less than max length
  1132. maxLength: function(value, maxLength) {
  1133. return (value !== undefined)
  1134. ? (value.length <= maxLength)
  1135. : false
  1136. ;
  1137. },
  1138. // value is not value (case insensitive)
  1139. not: function(value, notValue) {
  1140. value = (typeof value == 'string')
  1141. ? value.toLowerCase()
  1142. : value
  1143. ;
  1144. notValue = (typeof notValue == 'string')
  1145. ? notValue.toLowerCase()
  1146. : notValue
  1147. ;
  1148. return (value != notValue);
  1149. },
  1150. // value is not value (case sensitive)
  1151. notExactly: function(value, notValue) {
  1152. return (value != notValue);
  1153. },
  1154. // value is most likely url
  1155. url: function(value) {
  1156. return $.fn.form.settings.regExp.url.match(value);
  1157. }
  1158. }
  1159. };
  1160. })( jQuery, window , document );