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

Q538 How can I validate a form field so that leading zeros are dropped, any decimal places are dropped, any non numeric characters produce a warning, and if the resultant number is greater than 999 also produces a warning?

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

Try something like:

<script language="JavaScript"><!--
function validate(what) {
    what.output.value = '';

    for (var i=0, len=what.input.value.length-1, valid='0123456789.' ; i<len ; i++) {
        if (valid.indexOf(what.input.value.substring(i,i+1)) == -1) {
            alert('invalid data');
            return;
        }
    }
    number = Math.floor(what.input.value - 0);

    if (number < 1000)
        what.output.value = number;
    else
        alert('Greater than 999');

    return;
}
//--></script>

<form onSubmit="return false">
Input: <input type="text" name="input">
<br>Output: <input type="text" name="output">
<br><input type="button" value="Validate" onClick="validate(this.form)">
</form>

©2018 Martin Webb