You are here: irt.org | FAQ | JavaScript | Number | Q354 [ previous next ]
1. break it up into three fields:
<FORM> <INPUT TYPE="TEXT" SIZE="3" MAXLENGTH="3"> - <INPUT TYPE="TEXT" SIZE="3" MAXLENGTH="3"> - <INPUT TYPE="TEXT" SIZE="6" MAXLENGTH="6"> </FORM>
2. break it up into three fields with automatic tabbing
<FORM> <INPUT TYPE="TEXT" SIZE="3" MAXLENGTH="3" onKeyUp="if (this.value.length == 3) this.form.second.focus()"> - <INPUT NAME="second" TYPE="TEXT" SIZE="3" MAXLENGTH="3" onKeyUp="if (this.value.length == 3) this.form.third.focus()"> - <INPUT NAME="third" TYPE="TEXT" SIZE="6" MAXLENGTH="6"> </FORM>
However, the value of the form fields in Netscape Navigator are not set until the focus has changed therefore the length property cannot be relied upon whilst the user is typing.
3. Validating the contents after the user has moved on from the field:
<SCRIPT LANGUAGE="JavaScript"><!-- function validate(string) { if (!string) return false; var Chars = "0123456789-"; for (var i = 0; i < string.length; i++) { if (Chars.indexOf(string.charAt(i)) == -1) return false; } return true; } //--></SCRIPT> <FORM> <INPUT TYPE="TEXT" SIZE="12" MAXLENGTH="12" onChange="if (!validate(this.value)) alert('Not Valid')"> </FORM>
4. Using Regular Expressions:
<SCRIPT LANGUAGE="JavaScript"><!-- function regular(string) { if (!string) return false; var Chars = "0123456789-"; for (var i = 0; i < string.length; i++) { if (Chars.indexOf(string.charAt(i)) == -1) return false; } return true; } //--></SCRIPT> <SCRIPT LANGUAGE="JavaScript1.2"><!-- function regular(string) { if (string.search(/^[0-9][0-9][0-9]\-[0-9][0-9][0-9]\-[0-9][0-9][0-9][0-9]$/) != -1) return true; else return false; } //--></SCRIPT> <FORM> <INPUT TYPE="TEXT" SIZE="12" MAXLENGTH="12" onChange="if (!regular(this.value)) alert('Not Valid')"> </FORM>