Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

Q354 How do I format a form field 10 digit only numeric string to conform to the specific phone number format 123-123-1234?

irt.org | Knowledge Base | JavaScript | Number | Q354 [ previous next ]

Q354 How do I format a form field 10 digit only numeric string to conform to the specific phone number format 123-123-1234?

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>

Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.