I want to get only positive values, is there any way to prevent it using only html
Please don't suggest validation method

- 142,137
- 41
- 261
- 360

- 22,202
- 18
- 80
- 129
-
5This thread answers the same question in much better extent: http://stackoverflow.com/questions/31575496/prevent-negative-inputs-in-form-input-type-number – PiotrWolkowski Mar 18 '16 at 17:24
-
What about the user (and not the developer)? If I type -3 I get a 3, and that is not what I meant! Absolutely makes to sense! just leave the -3 there and give me an explanation error. How come most developers think this terrible behavior is user friendly? I hate it when a developer breaks my keyboard without telling me. – Cesar Feb 23 '21 at 22:07
18 Answers
Use the min
attribute like this:
<input type="number" min="0">

- 2,237
- 27
- 30
- 38

- 20,316
- 7
- 33
- 39
-
7Here's a [more reliable reference source](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-min). – Álvaro González Jun 10 '15 at 10:15
-
366This will block a negative number from being entered using the arrow buttons / spinner. However, the user can still manually enter in a negative number and have that field's value read as a negative number, thus bypassing the min attribute. – ecbrodie Jul 14 '15 at 15:49
-
89@demaniak No. And how did this answer get so many upvotes when it half answers the question is a mystery – GôTô Nov 17 '15 at 13:14
-
1@Abraham What if the data loaded with the -ve value in the form, it does not mark it as red. – Kamini Nov 04 '16 at 05:36
-
-
-
10This doesn't work, the user can still enter a negative number manually. – Altef four Nov 21 '17 at 20:04
-
i just tried entering a negative number manually and it stopped it.... not sure why all the comments about this not working. could of course be user error :) – russiansummer Apr 20 '18 at 16:57
-
5I can still copy paste negative values into the input field. I will look for another solution. This one doesn't work completely for me. – Ankit Vij Aug 02 '18 at 12:05
-
-
I was looking for upper bound. This answer guided me towards `max=1000`. (*upvoted) :-) – Tanzeel Nov 28 '19 at 09:34
-
1I used this, when I entered negative number it let me in, but did not let me submit, so I would say the code works as it should. – Ferazhu Oct 08 '20 at 13:50
-
@Abraham The answer should cover all corner cases. I am able to copy paste the -1 and able to type as well. – Javed Shaikh Dec 07 '20 at 17:05
For me the solution was:
<input type="number" min="0" oninput="this.value = Math.abs(this.value)">
Edit
As suggested on the comments with a minor change to work if 0 is the min value.
<input type="number" min="0" oninput="this.value =
!!this.value && Math.abs(this.value) >= 0 ? Math.abs(this.value) : null">

- 2,270
- 1
- 10
- 7
-
3Really best solution once you use pattern and noformvalidate with angular , since the model is not updated if not within the range. My case : `` – sebius Dec 07 '17 at 15:38
-
1this works best when user knows the default value is 0. Other wise user get confused on backspace press why field is not clearing. Except this, it is best solution.+1 – Deep 3015 Jan 25 '18 at 11:25
-
1This one works best, and in case of using decimal also. I had used other answer above, it stopped working when decimal is to be allowed. Is there way we can move this answer to up so-that people can use this mostly. – Subhan Ahmed Mar 06 '20 at 11:42
-
2If you want to keep blank after filling (e.g. with backspace) you should use this `this.value = Math.abs(this.value) > 0 ? Math.abs(this.value) : null` – ali6p Aug 18 '20 at 22:54
-
1I think ali6p's comment is the most useful. It's more user-friendly. Perhaps this answer can be updated with both versions. – Pete Adam Bialecki Sep 17 '20 at 15:38
-
-
1The only working solution with no negative inputs, no negative copy/paste, no negaive scroll. – Bharat Oct 10 '20 at 12:00
-
Brilliant. Also solves this style of input preventing .NET validation. Should be accepted answer. – graphicdivine Jun 08 '21 at 10:59
-
-
Tried to use this and its working with Chrome and Firefox but not in IE. Is there a way on how will it work with IE as well ? Thank you. – natsumiyu Oct 19 '21 at 05:47
-
-
I was not satisfied with @Abhrabm answer because:
It was only preventing negative numbers from being entered from up/down arrows, whereas user can type negative number from keyboard.
Solution is to prevent with key code:
// Select your input element.
var number = document.getElementById('number');
// Listen for input event on numInput.
number.onkeydown = function(e) {
if(!((e.keyCode > 95 && e.keyCode < 106)
|| (e.keyCode > 47 && e.keyCode < 58)
|| e.keyCode == 8)) {
return false;
}
}
<form action="" method="post">
<input type="number" id="number" min="0" />
<input type="submit" value="Click me!"/>
</form>
Clarification provided by @Hugh Guiney:
What key codes are being checked:
- 95, < 106 corresponds to Numpad 0 through 9;
- 47, < 58 corresponds to 0 through 9 on the Number Row; and 8 is Backspace.
So this script is preventing invalid key from being entered in input.
-
25Upvoted but I think it would help to clarify what key codes are being checked: > 95, < 106 corresponds to Numpad 0 through 9; > 47, < 58 corresponds to 0 through 9 on the Number Row; and 8 is Backspace. So this script is preventing any key but those from being entered. It's thorough but I think it might be overkill for browsers that natively support number inputs, which already filter out alphabetical keys (except for characters like "e" which can have a numerical meaning). It would probably suffice to prevent against 189 (dash) and 109 (subtract). And then combine with `min="0"`. – Hugh Guiney Feb 22 '16 at 16:31
-
3@Manwal It restricts to copy and paste numbers using keyboard. And allows me to copy paste negative numbers using mouse. – Beniton Fernando Jul 05 '16 at 14:05
-
1@Beniton Thanks giving this use case. Can you give me little idea about what you are doing.Always I can help you out. Please provide little runnable code or fiddle. You can have form Submit level validation for in your code. Although i always have check in **Backend** if i don't allow negative numbers. – Manwal Jul 05 '16 at 15:31
-
1Just copy-paste into the field basically. It's not really a special case or anything. Instead of handling the validation via keycode, it's probably better to do it onChange or focusOut and build a little validation function to catch any negative numbers. – ulisesrmzroche Jul 05 '16 at 21:03
-
I support @HughGuiney's advice, especially since this answer prevents arrow keys from being used to move around input field. – Fred Vollmer Jan 05 '17 at 22:37
-
-
I went with Hugh Guiney's method but added `e.preventDefault()` as well which seemed to prevent onChange (React) from firing. – Ben Creasy Aug 29 '17 at 21:50
-
@BenCreasy It will disable that event at all. Then you can't change the numbers from arrows. – Manwal Aug 30 '17 at 04:04
-
the `e.preventDefault()` only applies when I'm returning false for dash and subtract per Hugh's method - wasn't working otherwise in my case – Ben Creasy Aug 30 '17 at 06:24
-
3Condition for arrow key(37, 38, 39, 41) should also be put. `|| (e.keyCode>36 && e.keyCode<41)` This does not allow user to increase/decrease number through up/down arrow and go right/left to edit number. – vusan Jun 20 '19 at 05:39
-
Does this work if the user has some other way of putting in the value, such as pasting `-15` from the clipboard? – lmat - Reinstate Monica Dec 09 '21 at 16:12
This code is working fine for me. Can you please check:
<input type="number" name="test" min="0" oninput="validity.valid||(value='');">

- 3,236
- 8
- 62
- 93
-
5This works but emptying the entire input after you try to type `-` is not really a good idea. – extempl Jun 10 '17 at 02:47
-
15@extempl Sounds like a fair punishment to the user trying to enter a negative in a field where common sense indicates there are no negatives. – KhoPhi Nov 20 '17 at 01:12
-
4
-
@Rexford I agree, But I have set `min="0"` so there are no nagatives. If you want to negative value then remove this attribute. – Chinmay235 Apr 16 '18 at 09:16
-
1
-
1I tried this but it also prevented numbers with decimal points from being entered. – Len May 16 '19 at 02:42
-
It is not a good solution. it will break in decimal value. When you add 23.5 it automatically removed decimal and show 235 which is not ok. – Sunny Sep 18 '20 at 16:19
-
@Sunny As per the question. I have answered this. Here is asking for an only a positive number. – Chinmay235 Sep 22 '20 at 10:06
Easy method:
<input min='0' type="number" onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57">

- 415
- 5
- 4
I wanted to allow decimal numbers and not clear the entire input if a negative was inputted. This works well in chrome at least:
<input type="number" min="0" onkeypress="return event.charCode != 45">

- 4,634
- 4
- 32
- 42
-
How can add more ascii number here. for eg. with 45 i wana add 46 also. How it can be done? – Pradeep Singh Nov 21 '18 at 07:44
-
3@PradeepSingh "return [45, 46].indexOf(event.charCode) == -1" – ykay says Reinstate Monica Nov 23 '18 at 09:32
-
Please think out of the box. Are you really sure a `keypress` is the only way one could enter a negative number into an input... – Roko C. Buljan Sep 13 '19 at 11:23
The @Manwal answer is good, but i like code with less lines of code for better readability. Also i like to use onclick/onkeypress usage in html instead.
My suggested solution does the same: Add
min="0" onkeypress="return isNumberKey(event)"
to the html input and
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode;
return !(charCode > 31 && (charCode < 48 || charCode > 57));
}
as a javascript function.
As said, it does the same. It's just personal preference on how to solve the problem.

- 117
- 1
- 3
Here's an angular 2 solution:
create a class OnlyNumber
import {Directive, ElementRef, HostListener} from '@angular/core';
@Directive({
selector: '[OnlyNumber]'
})
export class OnlyNumber {
// Allow decimal numbers. The \. is only allowed once to occur
private regex: RegExp = new RegExp(/^[0-9]+(\.[0-9]*){0,1}$/g);
// Allow key codes for special events. Reflect :
// Backspace, tab, end, home
private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home'];
constructor(private el: ElementRef) {
}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
// Allow Backspace, tab, end, and home keys
if (this.specialKeys.indexOf(event.key) !== -1) {
return;
}
// Do not use event.keycode this is deprecated.
// See: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
let current: string = this.el.nativeElement.value;
// We need this because the current value on the DOM element
// is not yet updated with the value from this event
let next: string = current.concat(event.key);
if (next && !String(next).match(this.regex)) {
event.preventDefault();
}
}
}
add OnlyNumber to declarations in app.module.ts and use like it like this anywhere in your app
<input OnlyNumber="true">

- 7,326
- 14
- 70
- 104
-
Is there a way of allowing Paste for this? Also I changed the regex to: /^-?[0-9]+(\.[0-9]*){0,1}$/g to allow negative numbers, but it doesn't seem to work? – Dave Nottage Sep 22 '17 at 02:23
Just for reference: with jQuery you can overwrite negative values on focusout with the following code:
$(document).ready(function(){
$("body").delegate('#myInputNumber', 'focusout', function(){
if($(this).val() < 0){
$(this).val('0');
}
});
});
This does not replace server side validation!

- 1,696
- 18
- 32
-
This works fine **IF** the user focuses out of the input field, however if they immediately press enter whilst still in the field; they can still enter a negative number. – NemyaNation Dec 12 '19 at 19:27
simply use min="0"
<v-text-field
v-model="abc"
class="ml-1 rounded-0"
outlined
dense
label="Number"
type="number"
min="0">
</v-text-field>

- 545
- 4
- 12
oninput="this.value=(this.value < Number(this.min) || this.value > Number(this.max)) ? '' : this.value;"

- 7,331
- 5
- 34
- 66

- 41
- 1
-
2While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Sudheesh Singanamalla Jan 27 '18 at 16:19
-
While this may be the correct answer, it lacks enough detail. Please explain _why_ this works. When using Stack Overflow, consider that this is a _living knowledge base_, answers that don't share knowledge are far less useful. – Marc LaFleur Jan 27 '18 at 16:21
Restrict the charcter (-) & (e) in type Number
<input type="number" onkeydown="return event.keyCode !== 69 && event.keyCode !== 189" />
Demo: https://stackblitz.com/edit/typescript-cwc9ge?file=index.ts

- 1,081
- 1
- 9
- 17
-
It still is accepting dash(negative) symbol on the numpad side of my keyboard. only restricting/blocking the dash(negative) symbol key on qwerty side of keyboard. – FAQi Mar 02 '21 at 13:10
Just adding another way of doing this (using Angular) if you don't wanna dirt the HTML with even more code:
You only have to subscribe to the field valueChanges and set the Value as an absolute value (taking care of not emitting a new event because that will cause another valueChange hence a recursive call and trigger a Maximum call size exceeded error)
HTML CODE
<form [formGroup]="myForm">
<input type="number" formControlName="myInput"/>
</form>
TypeScript CODE (Inside your Component)
formGroup: FormGroup;
ngOnInit() {
this.myInput.valueChanges
.subscribe(() => {
this.myInput.setValue(Math.abs(this.myInput.value), {emitEvent: false});
});
}
get myInput(): AbstractControl {
return this.myForm.controls['myInput'];
}

- 1,167
- 14
- 22
<input type="number" name="credit_days" pattern="[^\-]+"
#credit_days="ngModel" class="form-control"
placeholder="{{ 'Enter credit days' | translate }}" min="0"
[(ngModel)]="provider.credit_days"
onkeypress="return (event.charCode == 8 || event.charCode == 0 ||
event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <=
57" onpaste="return false">
The answer to this is not helpful. as its only works when you use up/down keys, but if you type -11 it will not work. So here is a small fix that I use
this one for integers
$(".integer").live("keypress keyup", function (event) {
// console.log('int = '+$(this).val());
$(this).val($(this).val().replace(/[^\d].+/, ""));
if (event.which != 8 && (event.which < 48 || event.which > 57))
{
event.preventDefault();
}
});
this one when you have numbers of price
$(".numeric, .price").live("keypress keyup", function (event) {
// console.log('numeric = '+$(this).val());
$(this).val($(this).val().replace(/[^0-9\,\.]/g, ''));
if (event.which != 8 && (event.which != 44 || $(this).val().indexOf(',') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});

- 2,160
- 1
- 21
- 27
This solution allows all keyboard functionality including copy paste with keyboard. It prevents pasting of negative numbers with the mouse. It works with all browsers and the demo on codepen uses bootstrap and jQuery. This should work with non english language settings and keyboards. If the browser doesn't support the paste event capture (IE), it will remove the negative sign after focus out. This solution behaves as the native browser should with min=0 type=number.
Markup:
<form>
<input class="form-control positive-numeric-only" id="id-blah1" min="0" name="nm1" type="number" value="0" />
<input class="form-control positive-numeric-only" id="id-blah2" min="0" name="nm2" type="number" value="0" />
</form>
Javascript
$(document).ready(function() {
$("input.positive-numeric-only").on("keydown", function(e) {
var char = e.originalEvent.key.replace(/[^0-9^.^,]/, "");
if (char.length == 0 && !(e.originalEvent.ctrlKey || e.originalEvent.metaKey)) {
e.preventDefault();
}
});
$("input.positive-numeric-only").bind("paste", function(e) {
var numbers = e.originalEvent.clipboardData
.getData("text")
.replace(/[^0-9^.^,]/g, "");
e.preventDefault();
var the_val = parseFloat(numbers);
if (the_val > 0) {
$(this).val(the_val.toFixed(2));
}
});
$("input.positive-numeric-only").focusout(function(e) {
if (!isNaN(this.value) && this.value.length != 0) {
this.value = Math.abs(parseFloat(this.value)).toFixed(2);
} else {
this.value = 0;
}
});
});

- 800
- 4
- 10
Here is a solution that worked best of me for a QTY field that only allows numbers.
// Only allow numbers, backspace and left/right direction on QTY input
if(!((e.keyCode > 95 && e.keyCode < 106) // numpad numbers
|| (e.keyCode > 47 && e.keyCode < 58) // numbers
|| [8, 9, 35, 36, 37, 39].indexOf(e.keyCode) >= 0 // backspace, tab, home, end, left arrow, right arrow
|| (e.keyCode == 65 && (e.ctrlKey === true || e.metaKey === true)) // Ctrl/Cmd + A
|| (e.keyCode == 67 && (e.ctrlKey === true || e.metaKey === true)) // Ctrl/Cmd + C
|| (e.keyCode == 88 && (e.ctrlKey === true || e.metaKey === true)) // Ctrl/Cmd + X
|| (e.keyCode == 86 && (e.ctrlKey === true || e.metaKey === true)) // Ctrl/Cmd + V
)) {
return false;
}

- 1,978
- 20
- 16
If Number is Negative or Positive Using ES6’s Math.Sign
const num = -8;
// Old Way
num === 0 ? num : (num > 0 ? 1 : -1); // -1
// ES6 Way
Math.sign(num); // -1

- 1,040
- 13
- 7