Table of Contents for
The Modern Web

Version ebook / Retour

Cover image for bash Cookbook, 2nd Edition The Modern Web by Peter Gasston Published by No Starch Press, 2013
  1. The Modern Web
  2. Cover
  3. The Modern Web
  4. Advance Praise for
  5. Praise for Peter Gasston’s
  6. Dedication
  7. About the Author
  8. About the Technical Reviewer
  9. Acknowledgments
  10. Introduction
  11. The Device Landscape
  12. The Multi-screen World
  13. Context: What We Don’t Know
  14. What You’ll Learn
  15. A. Further Reading
  16. 1. The Web Platform
  17. A Quick Note About Terminology
  18. Who You Are and What You Need to Know
  19. Getting Our Terms Straight
  20. The Real HTML5
  21. CSS3 and Beyond
  22. Browser Support
  23. Test and Test and Test Some More
  24. Summary
  25. B. Further Reading
  26. 2. Structure and Semantics
  27. New Elements in HTML5
  28. WAI-ARIA
  29. The Importance of Semantic Markup
  30. Microformats
  31. RDFa
  32. Microdata
  33. Data Attributes
  34. Web Components: The Future of Markup?
  35. Summary
  36. C. Further Reading
  37. 3. Device-Responsive CSS
  38. Media Queries
  39. Media Queries in JavaScript
  40. Adaptive vs. Responsive Web Design
  41. Viewport-Relative Length Units
  42. Responsive Design and Replaced Objects
  43. Summary
  44. D. Further Reading
  45. 4. New Approaches to CSS Layouts
  46. Multi-columns
  47. Flexbox
  48. Grid Layout
  49. The Further Future
  50. Summary
  51. E. Further Reading
  52. 5. Modern JavaScript
  53. New in JavaScript
  54. JavaScript Libraries
  55. Polyfills and Shims
  56. Testing and Debugging
  57. Summary
  58. F. Further Reading
  59. 6. Device Apis
  60. Geolocation
  61. Orientation
  62. Fullscreen
  63. Vibration
  64. Battery Status
  65. Network Information
  66. Camera and Microphone
  67. Web Storage
  68. Drag and Drop
  69. Interacting with Files
  70. Mozilla’s Firefox OS and WebAPIs
  71. PhoneGap and Native Wrappers
  72. Summary
  73. G. Further Reading
  74. 7. Images and Graphics
  75. Comparing Vectors and Bitmaps
  76. Scalable Vector Graphics
  77. The canvas Element
  78. When to Choose SVG or Canvas
  79. Summary
  80. H. Further Reading
  81. 8. New Forms
  82. New Input Types
  83. New Attributes
  84. Datalists
  85. On-Screen Controls and Widgets
  86. Displaying Information to the User
  87. Client-side Form Validation
  88. The Constraint Validation API
  89. Forms and CSS
  90. Summary
  91. I. Further Reading
  92. 9. Multimedia
  93. The Media Elements
  94. Media Fragments
  95. The Media API
  96. Media Events
  97. Advanced Media Interaction
  98. Summary
  99. J. Further Reading
  100. 10. Web Apps
  101. Web Apps
  102. Hybrid Apps
  103. TV Apps
  104. Webinos
  105. Application Cache
  106. Summary
  107. K. Further Reading
  108. 11. The Future
  109. Web Components
  110. The Future of CSS
  111. Summary
  112. L. Further Reading
  113. M. Browser Support as of March 2013
  114. The Browsers in Question
  115. Enabling Experimental Features
  116. Chapter 1: The Web Platform
  117. Chapter 2: Structure and Semantics
  118. Chapter 3: Device-Responsive CSS
  119. Chapter 4: New Approaches to CSS Layouts
  120. Chapter 5: Modern JavaScript
  121. Chapter 6: Device APIs
  122. Chapter 7: Images and Graphics
  123. Chapter 8: New Forms
  124. Chapter 9: Multimedia
  125. Chapter 10: Web Apps
  126. Chapter 11: The Future
  127. N. Further Reading
  128. Introduction
  129. Chapter 1: The Web Platform
  130. Chapter 2: Structure and Semantics
  131. Chapter 3: Device-Responsive CSS
  132. Chapter 4: New Approaches to CSS Layouts
  133. Chapter 5: Modern JavaScript
  134. Chapter 6: Device APIs
  135. Chapter 7: Images and Graphics
  136. Chapter 8: New Forms
  137. Chapter 9: Multimedia
  138. Chapter 10: Web Apps
  139. Chapter 11: The Future
  140. Index
  141. About the Author
  142. Copyright

The Constraint Validation API

Native form validation is great, but at times you may want to do more with it by perhaps adding some custom validation or creating your own error-reporting framework. The Constraint Validation API has a series of objects, properties, and methods aimed at giving you the flexibility to extend the browser’s validation system or to roll your own.

The first property is willValidate, which returns true or false if the element it’s called on will be validated—not if its value is valid, but if the validation process will be applied. You might find it more useful to think of the property as willBeValidated. By default, all form elements return true, unless they are explicitly set not to—for example, by using the disabled attribute.

You could use willValidate to run actions only on form elements that will be validated, as in this code:

var inputFields = document.querySelectorAll('input'),
    inputLen = inputFields.length,
    i;
for (i = 0; i < inputLen; i++) {
  if (inputFields[i].willValidate) {
    // Do something
  }
}

The simplest way to validate an element in a form is to use the checkValidity() method, which returns true or false depending on whether the element it’s called on will validate with its current value. This method is at the core of the following script, in which the function checkStatus is used to run the checkValidity() method and update the contents of a sibling p element with a check or cross, depending on its validation status.

The function is attached to the email input using a listener for the input event, which is new to HTML5. This event fires whenever the value of an input or textarea element is updated—sort of similar to the keypress event—but it allows for the user entering blocks of text before firing on a pause or on the use of auto-suggested values:

var email = document.getElementById('email');
function checkStatus(e) {
  var valid= e.currentTarget.checkValidity(),
  validMsg = e.currentTarget.nextSibling,
  status = (valid) ? '✓' : '×';
  validMsg.textContent = status;
}
email.addEventListener('input', checkStatus, false);

You can try this in the example file checkvalidity.html, which also runs the script on a tel input that accepts only numbers.

As well as the input event, HTML5 brings us the invalid event. This event is fired on an element with an invalid value when either the form is submitted or the checkValidity() method is run and returns a standard HTMLEvent object. That being the case, I could update the previous code to attach an extra event listener to each field, logging the invalid event whenever it occurs:

inputField[i].addEventListener('invalid', logInvalid, false);

If you want to get information about why a value doesn’t validate, you can use the validity property. This property returns a validityState object with a range of properties related to validity; for example, if the field is required but contains no value, the valueMissing property returns true; or, if there are no validation errors, the valid property returns true.

The following script builds on the previous one by displaying a status message if the checkValidity() method returns false. It uses the validity property to check if a few common statuses are true and outputs a custom message if so, or a message of “Unknown error” in other cases:

var email = document.getElementById('email');
function statusMsg(e) {
  var valid= e.currentTarget.checkValidity(),
      validStatus = e.currentTarget.validity,
      validMsg = e.currentTarget.nextSibling,
      status;
  if (valid) {
    status = '✓';
  } else {
    if (validStatus.patternMismatch) {
      status = 'Pattern mismatch';
    } else if (validStatus.typeMismatch) {
      status = 'Type mismatch';
    }
    …
  }
  validMsg.textContent = status;
}
email.addEventListener('input', statusMsg, false);

You can run this script for yourself in the file validitystate.html; check the console to see the validityState object, and explore the different true and false values. Figure 8-14 shows an example as logged in Firebug.

The validityState object logged in Firebug, showing the current state of validity for the form field
Figure 8-14. The validityState object logged in Firebug, showing the current state of validity for the form field

Browsers that have native validation alerts create their own messages that appear on screen; for example, submitting an empty input that has the required attribute applied displays the message “Please fill in this field” in Firefox. The validationMessage property holds this message when the field is in an invalid state; if the value of the field is valid, the validationMessage property is an empty string.

You can set the message using the setCustomValidity() method, which also allows you to set a custom validation rule. For example, in the following code, I have two tel input types, referred to as telHome and telWork, and I want to ensure that the two values are different. To do this, I add an input listener on telWork, and each time the user types in this field, the rule checks if the value is the same as telHome, and if it is, a custom validation message is created:

var telHome = document.getElementById('tel-home'),
    telWork = document.getElementById('tel-work');
telWork.addEventListener('input', function (e) {
  if (e.currentTarget.value === telHome.value) {
    telWork.setCustomValidity('Must be different');
  } else {
    telWork.setCustomValidity('');
  }
}, false);

Take a look at customvalidity.html to see this in action; you can see the result in Figure 8-15.

A custom error message created with setCustomValidity()
Figure 8-15. A custom error message created with setCustomValidity()