I am trying to validate custom input box as following
<div class="form-group">
<label for="inputNetwork" class="control-label">{{'DNS_PRIMARY' | translate}}</label>
<div class="control-content">
<p>
<input type="number" integer min="1" max="223"
class="ip-single-column" ng-model="network.dnsPrimary[0]" name="dnsP0" required ng-blur="dnsBlur('P', 0)"
ng-class="{'has-error': networkForm.dnsP0.$invalid}" validate-dns>.
<input type="number" integer min="0" max="255"
class="ip-single-column" ng-model="network.dnsPrimary[1]" name="dnsP1" required ng-blur="dnsBlur('P', 1)"
ng-class="{'has-error': networkForm.dnsP1.$invalid}" validate-dns>.
<input type="number" integer min="0" max="255"
class="ip-single-column" ng-model="network.dnsPrimary[2]" name="dnsP2" required ng-blur="dnsBlur('P', 2)"
ng-class="{'has-error': networkForm.dnsP2.$invalid}" validate-dns>.
<input type="number" integer min="0" max="254"
class="ip-single-column" ng-model="network.dnsPrimary[3]" name="dnsP3" required ng-blur="dnsBlur('P', 3)"
ng-class="{'has-error': networkForm.dnsP3.$invalid}" validate-dns>
</p>
</div>
$scope.dnsBlur= function(section, pos) {
var elem = $scope.network.dnsPrimary;
var i = pos;
if(section.endsWith('P')) {
// primary
switch(i) {
case 0:
if (angular.isUndefined(elem[i]) || (elem[i] < 1 && elem[i] > 223))
elem[i] = $scope.defaultDns[i];
break;
case 1:
// if (!elem[i] || (elem[i] < 0 && elem[i] > 254))
if (angular.isUndefined(elem[i]) || (elem[i] < 0 && elem[i] > 254))
elem[i] = $scope.defaultDns[i];
break;
case 2:
if (angular.isUndefined(elem[i]) || (elem[i] < 0 && elem[i] > 255))
elem[i] = $scope.defaultDns[i];
break;
case 3:
if (angular.isUndefined(elem[i]) || (elem[i] < 0 && elem[i] > 254))
elem[i] = $scope.defaultDns[i];
break;
}
}
}
}]).directive('validateDns', ['$rootScope',
function($rootScope) {
function link($scope, elem, attrs, c) {
$scope.$watch(attrs.ngModel, function(newValue, oldValue) {
c.$setValidity('outOfRange', true);
switch(c.$name.charAt(c.$name.length - 1)) {
case 0:
if (!$scope.network.dnsPrimary[i] || ($scope.network.dnsPrimary[i] < 1 && $scope.network.dnsPrimary[i] > 223))
c.$setValidity('outOfRange', false);
break;
case 1:
if (!$scope.network.dnsPrimary[i] || ($scope.network.dnsPrimary[i] < 0 && $scope.network.dnsPrimary[i] > 255))
c.$setValidity('outOfRange', false);
break;
case 2:
if (!$scope.network.dnsPrimary[i] || ($scope.network.dnsPrimary[i] < 0 && $scope.network.dnsPrimary[i] > 255))
c.$setValidity('outOfRange', false);
break;
case 3:
if (!$scope.network.dnsPrimary[i] || ($scope.network.dnsPrimary[i] < 0 && $scope.network.dnsPrimary[i] > 254))
c.$setValidity('outOfRange', false);
break;
}
});
}
return {
require: 'ngModel',
link: link
};
}
But when I trying to get input number in Blur() function.
It will get undefined when the input out or range. For example, input 999 but get undefined.
Is it anyway to get 999 in Blur()?
You have a problem in Blur or in the others decorators in there. The value of the field should be the actual value otherwise even if it is out of the specified range.
<form action="#" onsubmit="console.log(this.quantity.value);return false;">
Quantity:
<input type="number" name="quantity"
min="0" max="100" step="10" value="30" onblur="console.log(this.value);">
<input type="submit">
</form>
I found an answer at here Angular ng-model changes to undefined when checkbox on ng-repeat has the required attribute
But need AngularJS after 1.3.
I am using AngularJs 1.2. So, I need to find another way out.
Related
I am using angular material with reactive form where i have an input field of type number. I want to limit the value that user can enter in the textbox from 1 to 99. I am able to achieve this but i see the value for a fraction of seconds after key up and then the value is sliced as i have written the slice logic inside the keyup event. I tried writing this logic in keypress but it does not seem to work. I tried using event.stopPropogation() and preventDefault but no luck. Below is the code:
<input type="number"
matInput
min="1"
max="99"
#tempVar
autocomplete="off"
formControlName="noOfWeeks"
(keyup)="imposeMinMax(tempVar)"
(keypress)="numericOnly($event)"
/>
TS File
numericOnly(e): boolean {
return e.keyCode === 8 && e.keyCode === 46
? true
: !isNaN(Number(e.key));
}
imposeMinMax(el) {
if (
el.value != '' &&
(parseInt(el.value) < parseInt(el.min) ||
parseInt(el.value) > parseInt(el.max))
) {
el.value = el.value.toString().slice(0, 2);
}
}
I can suggest an approach, that makes use of the keydown event:
<input type="number"
matInput
min="1"
max="99"
#tempVar
autocomplete="off"
formControlName="noOfWeeks"
(keydown)="handleKeydown($event)"
/>
handleKeyDown(e) {
const typedValue = e.keyCode;
if (typedValue < 48 && typedValue > 57) {
// If the value is not a number, we skip the min/max comparison
return;
}
const typedNumber = parseInt(e.key);
const min = parseInt(e.target.min);
const max = parseInt(e.target.max);
const currentVal = parseInt(e.target.value) || '';
const newVal = parseInt(typedNumber.toString() + currentVal.toString());
if (newVal < min || newVal > max) {
e.preventDefault();
e.stopPropagation();
}
}
Certainly, this handleKeyDown method can be further extended, depending on your requirement.
I have a DHCP Scope input
<input name="dhcpscope" type="number" min="1" max="254" ng-model="dhcpscope" maxlength="3" size="3" ng-required="true">
It works perfectly for DHCP scope range from 1-254, but I also want to exclude the number 111.
How do I do that? Is there another HTML attribute that I can use?
Unless, Angular RegEx ng-pattern is the only way to go about this ...
This is one way to do it. Use JavaScript. Call function onchange and just do the same thing for any number you want to remove inside that function, I did it for 3 and 6. Enjoy!
var lastnum = 1;
function myFunction(x) {
if (x.value == 3 && lastnum < 3) {
x.value = 4;
} else if (x.value == 3 && lastnum > 3) {
x.value = 2;
}
if (x.value == 6 && lastnum < 6) {
x.value = 7;
} else if (x.value == 6 && lastnum > 6) {
x.value = 5;
}
lastnum = document.getElementById("myNum").value;
}
<input name="dhcpscope" type="number" min="1" max="254" ng-model="dhcpscope" maxlength="3" size="3" ng-required="true" value="1" id="myNum" onchange='myFunction(document.getElementById("myNum"))'>
I have type=number input field and I have set min and max values for it:
<input type="number" min="0" max="23" value="14">
When I change the time in the rendered UI using the little arrows on the right-hand side of the input field, everything works properly - I cannot go either above 23 or below 0. However, when I enter the numbers manually (using the keyboard), then neither of the restrictions has effect.
Is there a way to prevent anybody from entering whatever number they want?
Maybe Instead of using the "number" type you could use the "range" type which would restrict the user from entering in numbers because it uses a slide bar and if you wanted to configure it to show the current number just use JavaScript
With HTML5 max and min, you can only restrict the values to enter numerals. But you need to use JavaScript or jQuery to do this kind of change. One idea I have is using data- attributes and save the old value:
$(function () {
$("input").keydown(function () {
// Save old value.
if (!$(this).val() || (parseInt($(this).val()) <= 11 && parseInt($(this).val()) >= 0))
$(this).data("old", $(this).val());
});
$("input").keyup(function () {
// Check correct, else revert back to old value.
if (!$(this).val() || (parseInt($(this).val()) <= 11 && parseInt($(this).val()) >= 0))
;
else
$(this).val($(this).data("old"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="number" min="0" max="23" value="14" />
In some cases pattern can be used instead of min and max. It works correctly with required.
Despite the HTML5 enforcement of min and max on the up/down arrows of type=number control, to really make those values useful you still have to use Javascript.
Just save this function somewhere and call it on keyup for the input.
function enforceMinMax(el) {
if (el.value != "") {
if (parseInt(el.value) < parseInt(el.min)) {
el.value = el.min;
}
if (parseInt(el.value) > parseInt(el.max)) {
el.value = el.max;
}
}
}
<input type="number" min="0" max="23" value="14" onkeyup=enforceMinMax(this)>
<input type="number" min="0" onkeyup="if(value<0) value=0;" />
$(document).ready(function(){
$('input[type="number"]').on('keyup',function(){
v = parseInt($(this).val());
min = parseInt($(this).attr('min'));
max = parseInt($(this).attr('max'));
/*if (v < min){
$(this).val(min);
} else */if (v > max){
$(this).val(max);
}
})
})
Here is my contribution. Note that the v < min is commented out because I'm using Bootstrap which kindly points out to the user that the range is outside the 1-100 but wierdly doesn't highlight > max!
oninput="if(this.value>your_max_number)this.value=your_max_number;"
This works properly for me.
One event listener, No data- attribute.
You can simply prevent it by using following script:
$(document).on('keyup', 'input[name=quantity]', function() {
var _this = $(this);
var min = parseInt(_this.attr('min')) || 1; // if min attribute is not defined, 1 is default
var max = parseInt(_this.attr('max')) || 100; // if max attribute is not defined, 100 is default
var val = parseInt(_this.val()) || (min - 1); // if input char is not a number the value will be (min - 1) so first condition will be true
if (val < min)
_this.val(min);
if (val > max)
_this.val(max);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="form-control" name="quantity" max="250" min="1" value="">
The only problem is: You can't type - to get negative numbers if your min is lower than 0
This works for me I think you should try this you change the pattern according to your need
like you start from pattern 1
<input type="number" pattern="[0-9]{2}" min="0" max="23" value="14">
You can use html keyup event for restriction
<input type="number" min="0" max="23" value="14" onkeyup="if(value<0) value=0;if(value>23) value=23;">
Use this range method instead of number method.
$(function () {
$("#input").change(function () {
// Save old value.
$("#limit").val($("#input").val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="limit" name="limit" value="14" readonly><br>
<input type="range" id="input" name="input" min="0" max="23" value="14"/>
Forget the keydown or keyup: it won't let you enter like 15 or 20 if the min was set to 10!
Use the change event since this is where the input value goes in your business logic (ViewModel):
private _enforceMinMax = (input:HTMLInputElement) => {
console.log("input", input);
const v = parseFloat(input.value);
if(input.hasAttribute("min")) {
const min = parseFloat(input.min);
if(v < min) {
input.value = min+"";
}
}
if(input.hasAttribute("max")) {
const max = parseFloat(input.max);
if(v > max) {
input.value = max+"";
}
}
}
private _distanceChange = (event) => {
this._enforceMinMax(event.target);
...
$(document).on('keyup', 'input[type=number][min],input[type=number][max]', function () {
var _this = $(this);
if (_this.val() === "-")
return;
var val = parseFloat(_this.val());
if (_this.attr("min") !== undefined && _this.attr("min") !== "") {
var min = parseFloat(_this.attr('min'));
if (val < min)
_this.val(min);
}
if (_this.attr("max") !== undefined && _this.attr("max") !== "") {
var max = parseFloat(_this.attr('max'));
if (val > max)
_this.val(max);
}
});
$(document).on('change', 'input[type=number][step]', function () {
var _this = $(this);
var val = parseFloat(_this.val());
if (_this.attr("step") !== undefined && _this.attr("step") !== "") {
var step = parseFloat(_this.attr('step'));
if ((val % step) != 0)
_this.val(val - (val % step));
}
});
This work perfect for geographic coordinates when you have general function document EventListener "keydown" in my example i use bootstrap class.
<input type="text" name="X_pos" id="X_pos" class="form-control form-control-line" onkeydown="event.stopPropagation(); return(parseInt(event.key) >= 0 && parseInt(event.key) <= 9 && this.value+''+event.key <= 179 && this.value+''+event.key >= (-179)) || this.value.slice(-1) == '.' && parseInt(event.key) >= 0 && parseInt(event.key) <= 9 || event.keyCode == 8 || event.keyCode == 190 && String(this.value+''+event.key).match(/\./g).length <=1 || event.keyCode == 109 && String(this.value+''+event.key).length == 1 || event.keyCode == 189 && String(this.value+''+event.key).length == 1" style="width:100%;" placeholder="X" autocomplete="off">
If you want you can create a function with this code but i preferred this method.
Again, no solution truly solved my question. But combined the knowledge, it somehow worked
What I wanted is a true max/min validator (supporting int/float) for my input control without fancy html5 help
Accepted answer of #Praveen Kumar Purushothaman worked but its hardcoded min/max in the checking condition
#Vincent can help me dynamically validate the input field by max/min attributes but it is not generic and only validating the integer input.
To combine both answer
Below code works for me
function enforceMinMax(el){
if(el.value != ""){
if(parseFloat(el.value) < parseFloat(el.min)){
el.value = el.min;
}
if(parseFloat(el.value) > parseFloat(el.max)){
el.value = el.max;
}
}
}
$(function () {
$("input").keydown(function () {
enforceMinMax(this);
});
$("input").keyup(function () {
enforceMinMax(this);
});
});
For the DOM
<input type="number" min="0" max="1" step=".001" class="form-control">
Afterwards all my inputs are truly responsive on the min max attributes.
Solution to respect min and max if they are defined on an input type=number:
$(document).on("change","input[type=number][min!=undefined]",function(){if($(this).val()<$(this).attr("min")) $(this).val($(this).attr("min"))})
$(document).on("change","input[type=number][max!=undefined]",function(){if($(this).val()>$(this).attr("max")) $(this).val($(this).attr("max"))})
Here is my Vanilla JS approach of testing against the set min and max values of a given input element if they are set.
All input.check elements are included in the input check. The actual input check is triggered by the change event and not by keyup or keydown. This will give the user the opportunity to edit their number in their own time without undue interference.
const inps=document.querySelectorAll("input.check");
inps.forEach(inp=>{
// memorize existing input value (do once at startup)
inp.dataset.old=inp.value;
// Carry out checks only after input field is changed (=looses focus)
inp.addEventListener("change",()=>{
let v=+inp.value;
// console.log(v,inp.min,inp.max,inp.dataset.old);
if(inp.max!=""&&v>+inp.max || inp.min!=""&&v<+inp.min) inp.value=inp.dataset.old;
else inp.dataset.old=inp.value;
});
})
<input class="check" type="number" min="0.1" max="23.4" value="14" />
$(function () {
$("input").keydown(function () {
// Save old value.
if (!$(this).val() || (parseInt($(this).val()) <= 11 && parseInt($(this).val()) >= 0))
$(this).data("old", $(this).val());
});
$("input").keyup(function () {
// Check correct, else revert back to old value.
if (!$(this).val() || (parseInt($(this).val()) <= 11 && parseInt($(this).val()) >= 0))
;
else
$(this).val($(this).data("old"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="number" min="0" max="23" value="14" />
You can compare keyCode and return false if those keys aren't numbers
for e.g
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
<script>
function handleKeyDown(e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
e.preventDefault();
return false;
}
}
</script>
</head>
<body>
<input type="number" min="0" max="23" value="14" onkeydown="handleKeyDown(event)" />
</body>
</html>
if you still looking for the answer you can use input type="number".
min max work if it set in that order:
1-name
2-maxlength
3-size
4-min
5-max
just copy it
<input name="X" maxlength="3" size="2" min="1" max="100" type="number" />
when you enter the numbers/letters manually (using the keyboard), and submit a little message will appear in case of letters "please enter a number" in case of a number out of tha range "please select a value that is no more/less than .."
How to make HTML input tag only accept numbers?
I need to make sure that input field only takes numbers as input
value.
I want the user to be unable to type in any other characters other
than numbers.
User manually enters the number not a number scroll bar.
I am using the Meteor Js.And the code as shown below.
App.html
<head>
<title App</title>
</head>
<body>
{{> main}}
</body>
<template name="main">
<h1>Welcome to TICTACTOE App</h1>
<p><b>Layout Number :</b> <input type="text" id="no"></p>
</template>
App.js
if (Meteor.isClient)
{
Template.main.events
({
'keydown input#no' : function ()
{
// template data, if any, is available in 'this'
if (event.which == 13)
{ // 13 is the enter key event
console.log("You pressed enter key");
}
}
});
}
if (Meteor.isServer)
{
Meteor.startup(function ()
{
// code to run on server at startup
});
}
This should help you.
<input type="number" />
:)
Or Best way to use jQuery with keycodes:
jQuery("#yourInputId").keydown(function(event) {
// Allow: backspace, delete, tab, escape, enter and .
if ( jQuery.inArray(event.keyCode,[46,8,9,27,13,190]) !== -1 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
else {
// Ensure that it is a number and stop the keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
event.preventDefault();
}
}
});
See DEMO.
if you use HTML5 then
<input type="number" />
else
<script>
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
return !(charCode > 31 && (charCode < 48 || charCode > 57));
}
</script>
<input type="text" onkeypress="return isNumberKey(event);">
With HTML5 it's easy:
<input type="number" />
If HTML5 is not supported use jQuery events: Live Demo
<label for="number">Number: </label>
<input type="text" name="number" id="number" />
<script>
$('#number').keydown(function(){
$(this).val($(this).val().replace(/[^\d]/,''));
$(this).keyup(function(){
$(this).val($(this).val().replace(/[^\d]/,''));
});
});
</script>
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
<input type="someid" name="number" onkeypress="return isNumberKey(event)"/>
will work only with HTML 5.
If you want it to work for older browser as well you have to take help of javascript.
Try this
<input name="amount" type="text" value="Only number in here"/>
<script>
$('input[name=amount]').keyup(function(){
$(this).val($(this).val().replace(/[^\d]/,''));
});
</script>
You can also use the pattern attribute in html5:
<input type="text" name="name" pattern="[0-9]" title="Title" />
On any input you need filter, you only need put the onkeydown="return onlynumbers(event);"
code.
This is a generic code that will work on old HTML and does not need jQuery. :)
<script type="text/javascript">
function onlynumbers(e) {
if (e.shiftKey === true ) {
if (e.which == 9) {
return true;
}
return false;
}
if (e.which > 57) {
return false;
}
if (e.which==32) {
return false;
}
return true;
}
</script>
<input type="text" onkeydown="return onlynumbers(event);">
I want to get only positive values, is there any way to prevent it using only html
Please don't suggest validation method
Use the min attribute like this:
<input type="number" min="0">
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">
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.
This code is working fine for me. Can you please check:
<input type="number" name="test" min="0" oninput="validity.valid||(value='');">
Easy method:
<input min='0' type="number" onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57">
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">
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.
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">
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!
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
oninput="this.value=(this.value < Number(this.min) || this.value > Number(this.max)) ? '' : this.value;"
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>
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'];
}
<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();
}
});
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;
}
});
});
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;
}
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