Validating Text Fields


if (field.value.replace(/\s/g, "") == "") {   window.alert("Invalid data!");   field.focus(); 

Validation of user-supplied data can come in various flavors. Sometimes it is just important to check whether a mandatory field has been filled out; in other scenarios a thorough data validation has to be done.

In the preceding code (file mandatory.html), the data in a text field is checked. The replace() JavaScript method call globally removes whitespace (regular expression /\s/g) in the string and then checks if there is anything left, so that just space characters do not satisfy the "fill out this field" condition.

In the next listing, the data in the text field is validated against a regular expressiona U.S. postal code:

Validating a Field Against a Regular Expression (mandatory-regex.html)

<script language="JavaScript"   type="text/javascript"> function validate(field) {   var regex = /^\d{5}$/;   if (!regex.test(field.value)) {     window.alert("Invalid postal code!");     field.value = "";     field.focus();   } } </script> <form onsubmit="return checkform(this);">   US postal code <input type="text" name="code"                   onblur="validate(this);" /> </form> 




JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net