Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q551 When creating a form, how can I check to see if data entered in a text field contains all numerics?

You are here: irt.org | FAQ | JavaScript | Form | 5 | Q551 [ previous next ]

Try:

<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" onChange="if (!validate(this.value)) alert('Not Valid')">
</form>

Or using a regular expression:

<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]*$/) != -1)
         return true;
     else
         return false;
}
//--></script>


<form>
<input type="text" onChange="if (!regular(this.value)) alert('Not Valid')">
</form>

©2018 Martin Webb