Web Analytics Made Easy -
StatCounter how to force user enter number only in the text box and must be 7 digits? - CodingForum

Announcement

Collapse
No announcement yet.

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

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • how to force user enter number only in the text box and must be 7 digits?

    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)">
    Thanks.
    =====================================================
    From NinjaTurtle
    ++http://ohmygoh.blogspot.com|http://technology.ohmygoh.com++

  • #2
    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/man...p.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.

    Code:
    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();
        }
    }
    De gustibus non est disputandum.

    Comment

    Working...
    X