4

I have an html input box, but only numeric data is data. How can I enforce that?

7 Answers 7

11

You can use HTML5 to validate the type of your input without using JavaScript. However, this method is not (yet) supported by all browsers.

<input type="number" name="quantity" min="1" max="5">

Use the following attributes to specify restrictions (as described here):

  • max - specifies the maximum value allowed
  • min - specifies the minimum value allowed
  • step - specifies the legal number intervals
  • value - Specifies the default value
Sign up to request clarification or add additional context in comments.

2 Comments

still not supported by IE, works like a charm in chrome. For IE jquery os JS has to be used.
According to w3schools.com/tags/tag_input.asp, all attributes (max, min and step) are supported since IE 10... Haven't tested it though...
0

You will need an events to validate if the entered text is a number or not. See sample code

JS

function isValidChar(char){

    var txt = char;
    var found = false;
    var validChars = "0123456789"; //List of valid characters

    for(j=0;j<txt.length;j++){ //Will look through the value of text
        var c = txt.charAt(j);
        found = false;
        for(x=0;x<validChars.length;x++){
            if(c==validChars.charAt(x)){
                found=true;
                break;
            }
        }
        if(!found){
            //If invalid character is found remove it and return the valid character(s).
            document.getElementById('txtFld').value = char.substring(0, char.length -1);
            break;
        }
    }
}

HTML

<input type="text" id="txtFld" onKeyup="isValidChar(this.value);" />

See working code here jsfiddle

Though the code is a bit long you can minimize if you know how to use regular expression or a jquery.

3 Comments

@khachick Good point, well you can simple add the "." and "-" to the validChars. Anyway this code is not really intend for numeric and its not perfect. I just get it in my code, if numeric values validation is strict. There will be a need for other validation, like isNan()
there is a problem when any key is pressed for a long time, it will trim only the last char of the text.
@Javed Akram, your correct I did not check that event. Anyway adding additional events onKeyPress="isValidChar(this.value);" will solve that problem. Thanks for the information I'll check my existing code to fix for a possible effect in my application.
0

Try this and it is up to you to select the minimum number and maximum:

legend {
    background-color: #000;
    color: #fff;
    padding: 3px 6px;
}

.output {
    font: 1rem 'Fira Sans', sans-serif;
}

input,
label {
    width: 43%;
}

input {
    margin: 1rem 0;
}

label {
    display: inline-block;
    font-size: .8rem;
}

input:invalid + span:after {
    content: '✖';
    color: #f00;
    padding-left: 5px;
}

input:valid + span:after {
    content: '✓';
    color: #26b72b;
    padding-left: 5px;
}
 <span class="validity"></span>

<input type="number" id="userId" name="userId"
           placeholder="Min: 1, max: 10000"
           min="1" max="10000" />
    <span class="validity"></span>

Comments

-1

Number() is the function you want "123a" returns NAN

parseInt() truncates trailing letters "123a" returns 123

<input type="text" id="txtFld" onblur="if(!Number(this.value)){alert('not a number');}" />

2 Comments

You don't need to add the javascript: pseudo-protocol, this is not needed at all since Netscape...
0 is a number, but pops up the alert.
-1

Try this code. work even on ctrl+v(paste)...

<SCRIPT Language ="VBScript"> 

sub onlyNumber(idBox)

    Set objInl = CreateObject("VBScript.RegExp")

    objInl.Global = True

    objInl.Pattern = "[^0-9\-\.]"

    document.getElementById(idBox).value = objInl.Replace(document.getElementById(idBox).value, "")

    set objInl = nothing

end sub

</SCRIPT>

 <input type="text" id="txtFld" onKeyup="onlyNumber(this.id);" />

Comments

-2
<input name="txtnumbersOnly"  type="text" onkeypress="if (event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;">

Comments

-2

Use java script function as a validator. Or you can get the jquery funcations as well.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.