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.

702 lines
22 KiB

  1. /*
  2. * # Semantic - Form Validation
  3. * http://github.com/jlukic/semantic-ui/
  4. *
  5. *
  6. * Copyright 2013 Contributors
  7. * Released under the MIT license
  8. * http://opensource.org/licenses/MIT
  9. *
  10. */
  11. ;(function ( $, window, document, undefined ) {
  12. $.fn.form = function(fields, parameters) {
  13. var
  14. $allModules = $(this),
  15. settings = $.extend(true, {}, $.fn.form.settings, parameters),
  16. validation = $.extend({}, $.fn.form.settings.defaults, fields),
  17. namespace = settings.namespace,
  18. metadata = settings.metadata,
  19. selector = settings.selector,
  20. className = settings.className,
  21. error = settings.error,
  22. eventNamespace = '.' + namespace,
  23. moduleNamespace = 'module-' + namespace,
  24. moduleSelector = $allModules.selector || '',
  25. time = new Date().getTime(),
  26. performance = [],
  27. query = arguments[0],
  28. methodInvoked = (typeof query == 'string'),
  29. queryArguments = [].slice.call(arguments, 1),
  30. invokedResponse
  31. ;
  32. $allModules
  33. .each(function() {
  34. var
  35. $module = $(this),
  36. $field = $(this).find(selector.field),
  37. $group = $(this).find(selector.group),
  38. $message = $(this).find(selector.message),
  39. $prompt = $(this).find(selector.prompt),
  40. $submit = $(this).find(selector.submit),
  41. formErrors = [],
  42. element = this,
  43. instance = $module.data(moduleNamespace),
  44. module
  45. ;
  46. module = {
  47. initialize: function() {
  48. module.verbose('Initializing form validation', $module, validation, settings);
  49. if(settings.keyboardShortcuts) {
  50. $field
  51. .on('keydown' + eventNamespace, module.event.field.keydown)
  52. ;
  53. }
  54. $module
  55. .on('submit' + eventNamespace, module.validate.form)
  56. ;
  57. $field
  58. .on('blur' + eventNamespace, module.event.field.blur)
  59. ;
  60. $submit
  61. .on('click' + eventNamespace, module.submit)
  62. ;
  63. $field
  64. .on(module.get.changeEvent() + eventNamespace, module.event.field.change)
  65. ;
  66. module.instantiate();
  67. },
  68. instantiate: function() {
  69. module.verbose('Storing instance of module', module);
  70. instance = module;
  71. $module
  72. .data(moduleNamespace, module)
  73. ;
  74. },
  75. destroy: function() {
  76. module.verbose('Destroying previous module', instance);
  77. $module
  78. .off(eventNamespace)
  79. .removeData(moduleNamespace)
  80. ;
  81. },
  82. refresh: function() {
  83. module.verbose('Refreshing selector cache');
  84. $field = $module.find(selector.field);
  85. },
  86. submit: function() {
  87. module.verbose('Submitting form', $module);
  88. $module
  89. .submit()
  90. ;
  91. },
  92. event: {
  93. field: {
  94. keydown: function(event) {
  95. var
  96. $field = $(this),
  97. key = event.which,
  98. keyCode = {
  99. enter : 13,
  100. escape : 27
  101. }
  102. ;
  103. if( key == keyCode.escape) {
  104. module.verbose('Escape key pressed blurring field');
  105. $field
  106. .blur()
  107. ;
  108. }
  109. if(!event.ctrlKey && key == keyCode.enter && $field.is(selector.input) ) {
  110. module.debug('Enter key pressed, submitting form');
  111. $submit
  112. .addClass(className.down)
  113. ;
  114. $field
  115. .one('keyup' + eventNamespace, module.event.field.keyup)
  116. ;
  117. event.preventDefault();
  118. return false;
  119. }
  120. },
  121. keyup: function() {
  122. module.verbose('Doing keyboard shortcut form submit');
  123. $submit.removeClass(className.down);
  124. module.submit();
  125. },
  126. blur: function() {
  127. var
  128. $field = $(this),
  129. $fieldGroup = $field.closest($group)
  130. ;
  131. if( $fieldGroup.hasClass(className.error) ) {
  132. module.debug('Revalidating field', $field, module.get.validation($field));
  133. module.validate.field( module.get.validation($field) );
  134. }
  135. else if(settings.on == 'blur' || settings.on == 'change') {
  136. module.validate.field( module.get.validation($field) );
  137. }
  138. },
  139. change: function() {
  140. var
  141. $field = $(this),
  142. $fieldGroup = $field.closest($group)
  143. ;
  144. if( $fieldGroup.hasClass(className.error) ) {
  145. module.debug('Revalidating field', $field, module.get.validation($field));
  146. module.validate.field( module.get.validation($field) );
  147. }
  148. else if(settings.on == 'change') {
  149. module.validate.field( module.get.validation($field) );
  150. }
  151. }
  152. }
  153. },
  154. get: {
  155. changeEvent: function() {
  156. return (document.createElement('input').oninput !== undefined)
  157. ? 'input'
  158. : (document.createElement('input').onpropertychange !== undefined)
  159. ? 'propertychange'
  160. : 'keyup'
  161. ;
  162. },
  163. field: function(identifier) {
  164. module.verbose('Finding field with identifier', identifier);
  165. if( $field.filter('#' + identifier).size() > 0 ) {
  166. return $field.filter('#' + identifier);
  167. }
  168. else if( $field.filter('[name="' + identifier +'"]').size() > 0 ) {
  169. return $field.filter('[name="' + identifier +'"]');
  170. }
  171. else if( $field.filter('[data-' + metadata.validate + '="'+ identifier +'"]').size() > 0 ) {
  172. return $field.filter('[data-' + metadata.validate + '="'+ identifier +'"]');
  173. }
  174. return $('<input/>');
  175. },
  176. validation: function($field) {
  177. var
  178. rules
  179. ;
  180. $.each(validation, function(fieldName, field) {
  181. if( module.get.field(field.identifier).get(0) == $field.get(0) ) {
  182. rules = field;
  183. }
  184. });
  185. return rules || false;
  186. }
  187. },
  188. has: {
  189. field: function(identifier) {
  190. module.verbose('Checking for existence of a field with identifier', identifier);
  191. if( $field.filter('#' + identifier).size() > 0 ) {
  192. return true;
  193. }
  194. else if( $field.filter('[name="' + identifier +'"]').size() > 0 ) {
  195. return true;
  196. }
  197. else if( $field.filter('[data-' + metadata.validate + '="'+ identifier +'"]').size() > 0 ) {
  198. return true;
  199. }
  200. return false;
  201. }
  202. },
  203. add: {
  204. prompt: function(field, errors) {
  205. var
  206. $field = module.get.field(field.identifier),
  207. $fieldGroup = $field.closest($group),
  208. $prompt = $fieldGroup.find(selector.prompt),
  209. promptExists = ($prompt.size() !== 0)
  210. ;
  211. module.verbose('Adding inline error', field);
  212. $fieldGroup
  213. .addClass(className.error)
  214. ;
  215. if(settings.inline) {
  216. if(!promptExists) {
  217. $prompt = settings.templates.prompt(errors);
  218. $prompt
  219. .appendTo($fieldGroup)
  220. ;
  221. }
  222. $prompt
  223. .html(errors[0])
  224. ;
  225. if(!promptExists) {
  226. if(settings.transition && $.fn.transition !== undefined) {
  227. module.verbose('Displaying error with css transition', settings.transition);
  228. $prompt.transition(settings.transition + ' in', settings.duration);
  229. }
  230. else {
  231. module.verbose('Displaying error with fallback javascript animation');
  232. $prompt
  233. .fadeIn(settings.duration)
  234. ;
  235. }
  236. }
  237. }
  238. },
  239. errors: function(errors) {
  240. module.debug('Adding form error messages', errors);
  241. $message
  242. .html( settings.templates.error(errors) )
  243. ;
  244. }
  245. },
  246. remove: {
  247. prompt: function(field) {
  248. var
  249. $field = module.get.field(field.identifier),
  250. $fieldGroup = $field.closest($group),
  251. $prompt = $fieldGroup.find(selector.prompt)
  252. ;
  253. $fieldGroup
  254. .removeClass(className.error)
  255. ;
  256. if(settings.inline && $prompt.is(':visible')) {
  257. module.verbose('Removing prompt for field', field);
  258. if(settings.transition && $.fn.transition !== undefined) {
  259. $prompt.transition(settings.transition + ' out', settings.duration, function() {
  260. $prompt.remove();
  261. });
  262. }
  263. else {
  264. $prompt
  265. .fadeOut(settings.duration, function(){
  266. $prompt.remove();
  267. })
  268. ;
  269. }
  270. }
  271. }
  272. },
  273. validate: {
  274. form: function(event) {
  275. var
  276. allValid = true
  277. ;
  278. // reset errors
  279. formErrors = [];
  280. $.each(validation, function(fieldName, field) {
  281. if( !( module.validate.field(field) ) ) {
  282. allValid = false;
  283. }
  284. });
  285. if(allValid) {
  286. module.debug('Form has no validation errors, submitting');
  287. $module
  288. .removeClass(className.error)
  289. .addClass(className.success)
  290. ;
  291. $.proxy(settings.onSuccess, this)(event);
  292. }
  293. else {
  294. module.debug('Form has errors');
  295. $module.addClass(className.error);
  296. if(!settings.inline) {
  297. module.add.errors(formErrors);
  298. }
  299. return $.proxy(settings.onFailure, this)(formErrors);
  300. }
  301. },
  302. // takes a validation object and returns whether field passes validation
  303. field: function(field) {
  304. var
  305. $field = module.get.field(field.identifier),
  306. fieldValid = true,
  307. fieldErrors = []
  308. ;
  309. if(field.rules !== undefined) {
  310. $.each(field.rules, function(index, rule) {
  311. if( module.has.field(field.identifier) && !( module.validate.rule(field, rule) ) ) {
  312. module.debug('Field is invalid', field.identifier, rule.type);
  313. fieldErrors.push(rule.prompt);
  314. fieldValid = false;
  315. }
  316. });
  317. }
  318. if(fieldValid) {
  319. module.remove.prompt(field, fieldErrors);
  320. $.proxy(settings.onValid, $field)();
  321. }
  322. else {
  323. formErrors = formErrors.concat(fieldErrors);
  324. module.add.prompt(field, fieldErrors);
  325. $.proxy(settings.onInvalid, $field)(fieldErrors);
  326. return false;
  327. }
  328. return true;
  329. },
  330. // takes validation rule and returns whether field passes rule
  331. rule: function(field, validation) {
  332. var
  333. $field = module.get.field(field.identifier),
  334. type = validation.type,
  335. value = $field.val(),
  336. bracketRegExp = /\[(.*?)\]/i,
  337. bracket = bracketRegExp.exec(type),
  338. isValid = true,
  339. ancillary,
  340. functionType
  341. ;
  342. // if bracket notation is used, pass in extra parameters
  343. if(bracket !== undefined && bracket !== null) {
  344. ancillary = bracket[1];
  345. functionType = type.replace(bracket[0], '');
  346. isValid = $.proxy(settings.rules[functionType], $module)(value, ancillary);
  347. }
  348. // normal notation
  349. else {
  350. isValid = $.proxy(settings.rules[type], $field)(value);
  351. }
  352. return isValid;
  353. }
  354. },
  355. setting: function(name, value) {
  356. module.debug('Changing setting', name, value);
  357. if(value !== undefined) {
  358. if( $.isPlainObject(name) ) {
  359. $.extend(true, settings, name);
  360. }
  361. else {
  362. settings[name] = value;
  363. }
  364. }
  365. else {
  366. return settings[name];
  367. }
  368. },
  369. internal: function(name, value) {
  370. module.debug('Changing internal', name, value);
  371. if(value !== undefined) {
  372. if( $.isPlainObject(name) ) {
  373. $.extend(true, module, name);
  374. }
  375. else {
  376. module[name] = value;
  377. }
  378. }
  379. else {
  380. return module[name];
  381. }
  382. },
  383. debug: function() {
  384. if(settings.debug) {
  385. if(settings.performance) {
  386. module.performance.log(arguments);
  387. }
  388. else {
  389. module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
  390. module.debug.apply(console, arguments);
  391. }
  392. }
  393. },
  394. verbose: function() {
  395. if(settings.verbose && settings.debug) {
  396. if(settings.performance) {
  397. module.performance.log(arguments);
  398. }
  399. else {
  400. module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
  401. module.verbose.apply(console, arguments);
  402. }
  403. }
  404. },
  405. error: function() {
  406. module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
  407. module.error.apply(console, arguments);
  408. },
  409. performance: {
  410. log: function(message) {
  411. var
  412. currentTime,
  413. executionTime,
  414. previousTime
  415. ;
  416. if(settings.performance) {
  417. currentTime = new Date().getTime();
  418. previousTime = time || currentTime;
  419. executionTime = currentTime - previousTime;
  420. time = currentTime;
  421. performance.push({
  422. 'Element' : element,
  423. 'Name' : message[0],
  424. 'Arguments' : [].slice.call(message, 1) || '',
  425. 'Execution Time' : executionTime
  426. });
  427. }
  428. clearTimeout(module.performance.timer);
  429. module.performance.timer = setTimeout(module.performance.display, 100);
  430. },
  431. display: function() {
  432. var
  433. title = settings.name + ':',
  434. totalTime = 0
  435. ;
  436. time = false;
  437. clearTimeout(module.performance.timer);
  438. $.each(performance, function(index, data) {
  439. totalTime += data['Execution Time'];
  440. });
  441. title += ' ' + totalTime + 'ms';
  442. if(moduleSelector) {
  443. title += ' \'' + moduleSelector + '\'';
  444. }
  445. if($allModules.size() > 1) {
  446. title += ' ' + '(' + $allModules.size() + ')';
  447. }
  448. if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
  449. console.groupCollapsed(title);
  450. if(console.table) {
  451. console.table(performance);
  452. }
  453. else {
  454. $.each(performance, function(index, data) {
  455. console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
  456. });
  457. }
  458. console.groupEnd();
  459. }
  460. performance = [];
  461. }
  462. },
  463. invoke: function(query, passedArguments, context) {
  464. var
  465. maxDepth,
  466. found,
  467. response
  468. ;
  469. passedArguments = passedArguments || queryArguments;
  470. context = element || context;
  471. if(typeof query == 'string' && instance !== undefined) {
  472. query = query.split(/[\. ]/);
  473. maxDepth = query.length - 1;
  474. $.each(query, function(depth, value) {
  475. var camelCaseValue = (depth != maxDepth)
  476. ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
  477. : query
  478. ;
  479. if( $.isPlainObject( instance[value] ) && (depth != maxDepth) ) {
  480. instance = instance[value];
  481. }
  482. else if( $.isPlainObject( instance[camelCaseValue] ) && (depth != maxDepth) ) {
  483. instance = instance[camelCaseValue];
  484. }
  485. else if( instance[value] !== undefined ) {
  486. found = instance[value];
  487. return false;
  488. }
  489. else if( instance[camelCaseValue] !== undefined ) {
  490. found = instance[camelCaseValue];
  491. return false;
  492. }
  493. else {
  494. module.error(error.method);
  495. return false;
  496. }
  497. });
  498. }
  499. if ( $.isFunction( found ) ) {
  500. response = found.apply(context, passedArguments);
  501. }
  502. else if(found !== undefined) {
  503. response = found;
  504. }
  505. if($.isArray(invokedResponse)) {
  506. invokedResponse.push(response);
  507. }
  508. else if(typeof invokedResponse == 'string') {
  509. invokedResponse = [invokedResponse, response];
  510. }
  511. else if(response !== undefined) {
  512. invokedResponse = response;
  513. }
  514. return found;
  515. }
  516. };
  517. if(methodInvoked) {
  518. if(instance === undefined) {
  519. module.initialize();
  520. }
  521. module.invoke(query);
  522. }
  523. else {
  524. if(instance !== undefined) {
  525. module.destroy();
  526. }
  527. module.initialize();
  528. }
  529. })
  530. ;
  531. return (invokedResponse !== undefined)
  532. ? invokedResponse
  533. : this
  534. ;
  535. };
  536. $.fn.form.settings = {
  537. name : 'Form',
  538. namespace : 'form',
  539. debug : true,
  540. verbose : true,
  541. performance : true,
  542. keyboardShortcuts : true,
  543. on : 'submit',
  544. inline : false,
  545. transition : 'scale',
  546. duration : 150,
  547. onValid : function() {},
  548. onInvalid : function() {},
  549. onSuccess : function() { return true; },
  550. onFailure : function() { return false; },
  551. metadata : {
  552. validate: 'validate'
  553. },
  554. selector : {
  555. message : '.error.message',
  556. field : 'input, textarea, select',
  557. group : '.field',
  558. input : 'input',
  559. prompt : '.prompt',
  560. submit : '.submit'
  561. },
  562. className : {
  563. error : 'error',
  564. success : 'success',
  565. down : 'down',
  566. label : 'ui label prompt'
  567. },
  568. // errors
  569. error: {
  570. method : 'The method you called is not defined.'
  571. },
  572. templates: {
  573. error: function(errors) {
  574. var
  575. html = '<ul class="list">'
  576. ;
  577. $.each(errors, function(index, value) {
  578. html += '<li>' + value + '</li>';
  579. });
  580. html += '</ul>';
  581. return $(html);
  582. },
  583. prompt: function(errors) {
  584. return $('<div/>')
  585. .addClass('ui red pointing prompt label')
  586. .html(errors[0])
  587. ;
  588. }
  589. },
  590. rules: {
  591. checked: function() {
  592. return ($(this).filter(':checked').size() > 0);
  593. },
  594. empty: function(value) {
  595. return !(value === undefined || '' === value);
  596. },
  597. email: function(value){
  598. var
  599. emailRegExp = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")
  600. ;
  601. return emailRegExp.test(value);
  602. },
  603. length: function(value, requiredLength) {
  604. return (value !== undefined)
  605. ? (value.length >= requiredLength)
  606. : false
  607. ;
  608. },
  609. not: function(value, notValue) {
  610. return (value != notValue);
  611. },
  612. contains: function(value, text) {
  613. return (value.search(text) !== -1);
  614. },
  615. is: function(value, text) {
  616. return (value == text);
  617. },
  618. maxLength: function(value, maxLength) {
  619. return (value !== undefined)
  620. ? (value.length <= maxLength)
  621. : false
  622. ;
  623. },
  624. match: function(value, fieldIdentifier) {
  625. // use either id or name of field
  626. var
  627. $form = $(this),
  628. matchingValue
  629. ;
  630. if($form.find('#' + fieldIdentifier).size() > 0) {
  631. matchingValue = $form.find('#' + fieldIdentifier).val();
  632. }
  633. else if($form.find('[name=' + fieldIdentifier +']').size() > 0) {
  634. matchingValue = $form.find('[name=' + fieldIdentifier + ']').val();
  635. }
  636. else if( $form.find('[data-validate="'+ fieldIdentifier +'"]').size() > 0 ) {
  637. matchingValue = $form.find('[data-validate="'+ fieldIdentifier +'"]').val();
  638. }
  639. return (matchingValue !== undefined)
  640. ? ( value.toString() == matchingValue.toString() )
  641. : false
  642. ;
  643. },
  644. url: function(value) {
  645. var
  646. urlRegExp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
  647. ;
  648. return urlRegExp.test(value);
  649. }
  650. }
  651. };
  652. })( jQuery, window , document );