...

View Full Version : how to force user enter number only in the text box and must be 7 digits?



NinjaTurtle
07-11-2002, 11:11 AM
dear,
this is how i check the integer.

function update(field) {
if (!/^-?\+?\d+$/.test(field.value)) {
alert('Please enter an integer value.');
field.focus();
field.select();

<input name="hp" type="text" class="txtbox" size="10" maxlength="7" value="" onblur="update(this)">

mordred
07-11-2002, 01:13 PM
You simply have to include in the RegExp how often a numerical digit (\d) has to appear with the {n} occurences characters. See also http://devedge.netscape.com/docs/manuals/js/core/jsguide15/regexp.html#1008327 for reference.

So drop the + after \d and your function would look like

function update(field) {
if (!/^-?\+?\d{7}$/.test(field.value)) {
alert('Please enter an integer value.');
field.focus();
field.select();
}
}

Because I see that you give the user the opportunity to have a +/- sign at the first position, I wonder how many numerical digits excluding the first sign you actually want to allow, because your maxlength attribute of the input tag is set to 7. I've written an extended function of yours that also returns different error messages. Change it to your needs, I assumed that this function operates on an input field with maxlength 8.



function update(field) {
if (!/^-?\+?\d+$/.test(field.value)) {
var errorMessage = "Please enter an integer value.";
}
else if (!/^[-+]?\d{7}$/.test(field.value)) {
var errorMessage = "Your integer value must be 7 digits long.";
}

// check to see which sort of error ocurred
if (typeof errorMessage != "undefined") {
alert(errorMessage);
field.focus();
field.select();
}
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum