Click to See Complete Forum and Search --> : Validation Help
Finder
11-27-2002, 01:12 AM
Hi I am new to Javascript. Is it possible to have a form field that can be submitted empty but when it is entered it must be a 6 digit number only.
I have experimented with onKeypress in the input field and it work great:
onKeypress="if (event.keyCode < 48 || event.keyCode > 57) event.returnValue = false;"
I have found a few scripts that can make the length 6 digits long but won't let an empty field submit.
Any help here would be very much appreciated :confused:
tobake
11-27-2002, 02:26 AM
here it is a good idea to use a regular expression.
here is a function that will do the job :
function validate() {
var re = /^(\d{6})$/; //reg exp that checks for six digits
if(document.form1.foo.value.length>0) {
if(!re.test(document.form1.foo.value)) {
alert("six digits please!")
}
}
}
Finder
11-27-2002, 03:16 AM
Thank very much tobake it works great. I have one more question: how do I return the focus to the field that does not have the six digits. This script continues to submit after the alert button is clicked.
I have played with the script a bit but am not experienced enough to know what I am doing.
function validate() {
var re = /^(\d{6})$/; //reg exp that
if(document.order.parcel1.value!="") {
if(!re.test(document.order.parcel1.value)) {
alert("six digits please!")
field.focus();
field.select();
return false;
}
}
}
tobake
11-27-2002, 03:21 AM
document.order.parcel1.select()
Use select() if you want to select the text in the field or focus() i you only want to give focus to the field.
Finder
11-27-2002, 03:42 AM
Thank you very much tobake for your time and help!!!