forms-validation.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // This implementation only tests support for interactive form validation.
  2. // To check validation for a specific type or a specific other constraint,
  3. // the test can be combined:
  4. // - Modernizr.inputtypes.numer && Modernizr.formvalidation (browser supports rangeOverflow, typeMismatch etc. for type=number)
  5. // - Modernizr.input.required && Modernizr.formvalidation (browser supports valueMissing)
  6. //
  7. (function(document, Modernizr){
  8. Modernizr.formvalidationapi = false;
  9. Modernizr.formvalidationmessage = false;
  10. Modernizr.addTest('formvalidation', function(){
  11. var form = document.createElement('form');
  12. if ( !('checkValidity' in form) ) {
  13. return false;
  14. }
  15. var body = document.body,
  16. html = document.documentElement,
  17. bodyFaked = false,
  18. invaildFired = false,
  19. input;
  20. Modernizr.formvalidationapi = true;
  21. // Prevent form from being submitted
  22. form.onsubmit = function(e) {
  23. //Opera does not validate form, if submit is prevented
  24. if ( !window.opera ) {
  25. e.preventDefault();
  26. }
  27. e.stopPropagation();
  28. };
  29. // Calling form.submit() doesn't trigger interactive validation,
  30. // use a submit button instead
  31. //older opera browsers need a name attribute
  32. form.innerHTML = '<input name="modTest" required><button></button>';
  33. // FF4 doesn't trigger "invalid" event if form is not in the DOM tree
  34. // Chrome throws error if invalid input is not visible when submitting
  35. form.style.position = 'absolute';
  36. form.style.top = '-99999em';
  37. // We might in <head> in which case we need to create body manually
  38. if ( !body ) {
  39. bodyFaked = true;
  40. body = document.createElement('body');
  41. //avoid crashing IE8, if background image is used
  42. body.style.background = "";
  43. html.appendChild(body);
  44. }
  45. body.appendChild(form);
  46. input = form.getElementsByTagName('input')[0];
  47. // Record whether "invalid" event is fired
  48. input.oninvalid = function(e) {
  49. invaildFired = true;
  50. e.preventDefault();
  51. e.stopPropagation();
  52. };
  53. //Opera does not fully support the validationMessage property
  54. Modernizr.formvalidationmessage = !!input.validationMessage;
  55. // Submit form by clicking submit button
  56. form.getElementsByTagName('button')[0].click();
  57. // Don't forget to clean up
  58. body.removeChild(form);
  59. bodyFaked && html.removeChild(body);
  60. return invaildFired;
  61. });
  62. })(document, window.Modernizr);