Tom wrote:
Hello,
When a visitor
enters a number into a textbox, I want to check that it is 15 digits long
and then display a message accordingly and the following script does that
OK. However, I want also to make sure that only "numbers" are entered and
no other characters.
res = isNaN(entry) ? "please enter only numbers": "Press OK to continue";
The isNaN function tests whether the entry is not a number, which
include all sorts of numbers, ranging from positive integers to floats
or numbers expressed using scientific notation. It seems to me that you
want some more restrictive test, accepting only unsigned integers.
if(length == 15) document.write( ok);
By doing this, you will start writing some new page. This isn't probably
what you have in mind, it is actually possible to update the current
document without having to rewrite it.
<URL:http://jibbering.com/faq/#FAQ4_15>
Any help would be greatly appreciated.
The best way to validate text input it to use "regular expressions".
These are expressions which can validate whether a string matches some
pattern. You can learn more about it here :
<URL:http://msdn.microsoft. com/library/default.asp?url =/library/en-us/script56/html/2380d458-3366-402b-996c-9363906a7353.as p>
Here goes some simple example which you might find useful.
---
<style type="text/css">
#bar-info { font-size:0.9em; }
..normal { color:#aaa; }
..warning { color:#c00; }
..valid { color:#0c0; }
</style>
<form action="#" name="foo">
<input
type="text"
maxlength="15"
name="bar"
onchange="updat e(this)"
onkeyup="update (this)"
onkeypress="upd ate(this)">
<span id="bar-info" class="normal"> Please enter 15 digits</span>
</form>
<script type="text/javascript">
function update(textFiel d){
if(document.get ElementById) {
var infoBox = document.getEle mentById("bar-info");
var value = textField.value ;
var messages = {
NORMAL : "Please enter 15 digits",
NUMBER : "Only numbers, please!",
DIGITS : "xx digits (15 required)",
VALID : "Entry validated."
}
if(value.length ==0) {
//field empty
infoBox.innerHT ML=messages.NOR MAL;
infoBox.classNa me="normal";
} else if(/\D/.test(value)) {
// one non digit char has been spotted
infoBox.innerHT ML=messages.NUM BER;
infoBox.classNa me="warning";
} else if(value.length !=15){
// Still not 15 digits
infoBox.innerHT ML=messages.DIG ITS.replace(/xx/,value.length);
infoBox.classNa me="normal";
} else {
// OK
infoBox.innerHT ML=messages.VAL ID;
infoBox.classNa me="valid";
}
}
}
</script>
---
Kind regards,
Elegie.