Click to See Complete Forum and Search --> : IsNaN one step further


theekx
11-18-2003, 03:31 PM
I have a form field that I am validating using the JavaScript function IsNaN. The variable "Number" is valid and contains the value of "5". The CGI program is expecting a 5 character long value that is zero filled (e.g. "00005"). Is there an easy way to do this?

As you can tell, I do not have much JavaScript knowledge.

Thanks.

Charles
11-18-2003, 03:36 PM
<input type="text" onchange="if (/^\d{5}$/.test(this.value)) {alert('That would not appear to be a valid value.'); this.value = ''; this.focus()}">

theekx
11-18-2003, 03:39 PM
Thanks a lot for your reply!

Is there a way to accept the "5" and automatically add the four leading zeros (e.g. "00005")?

Thanks

Charles
11-18-2003, 04:00 PM
<script type="text/javascript">
<!--
Number.prototype.toPadded = function (p) {var n = Number(this); var s = ''; if (/^0+$/.test(p) && n < 0) {s = '-'; n = Math.abs(n)}; return s + p.slice(0, 0 - n.toString().match(/^[^.]*/)[0].length) + n.toString()}
// -->
</script>

<input type="text" onchange="this.value = parseInt(this.value).toPadded(5); if (isNaN (this.value)) {alert('That would not appear to be a valid value.'); this.value = ''; this.focus()}">