Formatting and Validating Strings

Regular expressions can be used to simultaneously format and validate an entered value. In Script 8.7, the user enters a phone number in any format. Either the end result will be a formatted phone number or the input box will turn red and the label will turn red and bold.

Script 8.7. This script validates and formats a user-entered phone number.
window.onload = initForms; function initForms() { for (var i=0; i< document.forms.length; i++) { document.forms[i].onsubmit = function() {return validForm();} } } function validForm() { var allTags = document.getElementsByTagName("*"); for (var i=0; i<allTags.length; i++) { validTag(allTags[i]); } return false; function validTag(thisTag) { var outClass = ""; var allClasses ...

Get JavaScript and Ajax for the Web: Visual QuickStart Guide, Seventh Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.