Skip to content Skip to sidebar Skip to footer

Javascript Validation For Positive Integer Only Input

I have two text boxes, in it will only be allowed positive integers. If any alphabetical values or any other characters (e.g. %$&*£') are entered, an error message should be d

Solution 1:

Note: you can do this simply via HTML5 form validation:

<inputtype="number"min="1">

Then you won't be able to submit the form unless the entered value is a number higher than 1. This only seems to work in Chrome though.


To answer your question, what you're looking for is event.preventDefault(). If you change your onclick function to:

 <inputtype="button" value="total" name="B3" onclick="powerOf(event);">

then you can run event.preventDefault() in the powerOf function, and when you run that, the event will be "cancelled". For example:

functionpowerOf(event) {
    if (!/^\d+$/.test(document.getElementById('input-1').value)) {
        event.preventDefault();
    }
}

that will cancel the click event when the value of the input with id="input-1" is not digits only.

See this demo for a working example.

Post a Comment for "Javascript Validation For Positive Integer Only Input"