Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Jun 2002
    Posts
    358
    Thanks
    2
    Thanked 0 Times in 0 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
    Senior Coder
    Join Date
    Jun 2002
    Location
    frankfurt, german banana republic
    Posts
    1,848
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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();
        }
    }


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •