forms-validation.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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) || !('addEventListener' in form) ) {
  13. return false;
  14. }
  15. if ('reportValidity' in form) {
  16. return true;
  17. }
  18. var invalidFired = false;
  19. var input;
  20. Modernizr.formvalidationapi = true;
  21. // Prevent form from being submitted
  22. form.addEventListener('submit', function(e) {
  23. //Opera does not validate form, if submit is prevented
  24. if ( !window.opera ) {
  25. e.preventDefault();
  26. }
  27. e.stopPropagation();
  28. }, false);
  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. Modernizr.testStyles('#modernizr form{position:absolute;top:-99999em}', function( node ) {
  34. node.appendChild(form);
  35. input = form.getElementsByTagName('input')[0];
  36. // Record whether "invalid" event is fired
  37. input.addEventListener('invalid', function(e) {
  38. invalidFired = true;
  39. e.preventDefault();
  40. e.stopPropagation();
  41. }, false);
  42. //Opera does not fully support the validationMessage property
  43. Modernizr.formvalidationmessage = !!input.validationMessage;
  44. // Submit form by clicking submit button
  45. form.getElementsByTagName('button')[0].click();
  46. });
  47. return invalidFired;
  48. });
  49. })(document, window.Modernizr);