I just want to restrict user to input only 10 digits in a mobile number field.
I have tried this code
app.directive('allowOnlyNumbers', function () {
return {
restrict: 'A',
link: function (scope, elm, attrs, ctrl) {
elm.on('keydown', function (event) {
if (event.which == 64 || event.which == 16) {
// to allow numbers
return false;
} else if (event.which >= 48 && event.which <= 57) {
// to allow numbers
return true;
} else if (event.which >= 96 && event.which <= 105) {
// to allow numpad number
return true;
} else if ([8, 13, 27, 37, 38, 39, 40].indexOf(event.which) > -1) {
// to allow backspace, enter, escape, arrows
return true;
} else {
event.preventDefault();
// to stop others
return false;
}
});
}
}
});
This code allow users to input the numbers but it's taking more than 10 digits.
can anyone tell me how to restrict ofr only 10 digits only?
Any help will be appreciated.
Thanks in advance....
You could also try using ng-pattern:
<input type="text" class="form-control" ng-model="sample"
ng-pattern="/^[0-9]{10}$/">
This would require exactly 10 digits, and nothing else, for validation to pass. If you instead require a maximum of 10 digits, but fewer digits than this also acceptable, then you could use ^[0-9]{1,10}.
Just use maxlength attribute without directive
<input type="text" class="form-control" ng-model="sample" maxlength="10">
EDIT
Change it to type="number" if you want to have only numbers,
<input type="number" class="form-control" ng-model="sample" maxlength="10">
Related
I have a input box which should not allow negative decimal value and 0 trying to do using charcode as shown below
<input type="number" min="1" name="minValue"
className="input-box removeNumberArrow" value={this.state.minValue}
onChange={this.handleMinChange} onKeyPress={this.validateEntredVal}/>
Below method is called when ever a key is pressed
validateEntredVal = (event) => {
let charCode = (evt.which) ? evt.which : evt.keyCode;
if ((charCode > 31 && (charCode <48 || charCode > 57)) && charCode !== 46) {
evt.preventDefault();
} else {
return true;
}
};
Using the above method it will not allow the characters and negative values. problem it should not allow 0 and decimal as well (means the text box value should always accept value greater than zero)
Please help on the same
min="1" is not working
Add min="0" attribute in min tag.
I want to my textbox to only allow numbers and also have a character limit on it.
Currently, I have the numbers working... Now I am having issues figuring out how to limit the characters.
Here is what I have...
JS:
app.directive('numbersonly', function () {
return {
restrict: 'A',
link: function (scope, elm, attrs, ctrl) {
elm.on('keydown', function (event) {
if (event.which == 64 || event.which == 16 && elm.val().length > 4) {
return false;
} else if (event.which >= 48 && event.which <= 57) {
return true;
} else if (event.which >= 96 && event.which <= 105) {
return true;
} else if ([8, 13, 27, 37, 38, 39, 40].indexOf(event.which) > -1 && elm.val().length > 4) {
return true;
} else {
event.preventDefault();
return false;
}
});
}
}
});
Markup:
<input type="text" id="txtEmpAge" data-ng-model="newemployee.Age" class="form-control" numbersonly required />
In html input attribute length. we can use it in multiple forms:
Length, Minlength and maxlength
Try this
maxlength="5"
I had the same issue and wrote a directive to figure it all out. Then I found a plug in called angular-dynamic-number and it worked for me right out the box. I would suggest you use that if it meets your need.
https://www.npmjs.com/package/angular-dynamic-number
I want to make textbox numeric only in my Angular JS application.
Here is my code-
script.js
app.directive('numbersonly', function () {
return {
restrict: 'A',
link: function (scope, elm, attrs, ctrl) {
elm.on('keydown', function (event) {
if (event.which == 64 || event.which == 16) {
// to allow numbers
return false;
} else if (event.which >= 48 && event.which <= 57) {
// to allow numbers
return true;
} else if (event.which >= 96 && event.which <= 105) {
// to allow numpad number
return true;
} else if ([8, 13, 27, 37, 38, 39, 40].indexOf(event.which) > -1) {
// to allow backspace, enter, escape, arrows
return true;
} else {
event.preventDefault();
// to stop others
return false;
}
});
}
}
});
And on UI-
<input type="text" id="txtEmpAge" data-ng-model="newemployee.Age" class="form-control" numbersonly required />
But the text box is accepting both numeric and character.
If it is not necessary to use your own implementation, try Angular's number type input.
You can use type=number
<input type="number" id="txtEmpAge" data-ng-model="newemployee.Age" class="form-control" required />
This will take only number values in the text box.
in my opinion, best way to achieve
, it will also not allow user to copy paste strings to input
<input type="number" onkeypress='return event.charCode >= 48 && event.charCode <= 57'></input>
Use the following snippet to make the input field to accept only characters between 0 to 9. This will eliminate the decimal pointer.
<input type="number" onkeypress="return isNumKey(event)"/>
use this function to trigger on key is pressed.
function isNumKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
As demonstrative in the following code sample, the input named amountOrPercet can be interpreted as an amount or as a percentage value, depending on the state of the mode radio button.
<input type="radio" name="mode" value="amt" ng-model="mode"/> Amount
<input type="radio" name="mode" value="pct"ng-model="mode"/> Percent
<input type="text" name="amountOrPercent" ng-model="amountOrPercent" check-percent/>
I have put together an attribute directive to invalidate amountOrPercent for values greater than 100, in case it must be interpreted as a percentage:
myApp.directive('checkPct', function () {
return {
require: 'ngModel',
link: function (scope, elem, attr, ngModel) {
ngModel.$parsers.unshift(function (value) {
var valid = scope.mode != 'pct' || value <= 100;
ngModel.$setValidity('checkPct', valid);
return valid ? value : undefined;
});
ngModel.$formatters.unshift(function (value) {
ngModel.$setValidity('checkPct', scope.mode != 'pct' || value <= 100);
return value;
});
}
};
});
When the value of mode it kept unchanged, The validation works as expected. However when the value of mode is changed, the value of amountOrPercent is not re-validated, unless user changes the value of amountOrPercentage.
I know that I can use a watch to do some action based on changes in mode, but my question is how I can trigger the validation on amountOrPercent, when mode is changed. - Thank you
You can add watcher for mode and revalidate value when it changes:
scope.$watch('mode', function(){
var valid = scope.mode != 'pct' || ngModel.$modelValue <= 100;
ngModel.$setValidity('checkPct', valid);
}
I have a form, that has one input field and three check boxes. Depending on which check box is selected the max length on the field needs to change. I have a input field defined like this
<input placeholder="ID" type="text" id="form_ID" name="searchId" autofocus
data-ng-model="vm.searchCriteria.searchId" data-ng-required="vm.isSearchIdRequired"
data-ng-minlength="1" data-ng-maxlength="{{searchIdMaxLength}}"
data-ng-class="{'input-error': vm.isSearchIdValid}">
and one of the checkboxes
<input type="checkbox" id="checkbox1" class="hidden-field"
data-ng-model="vm.searchCriteria.searchIdInSrId" data-ng-checked="vm.searchCriteria.searchIdInSrId"
data-ng-change="processSearchIdOptionsChange()">
So everytime user changes which checkbox is/are selected processSearchIdOptionsChange gets called, and searchIdMaxLength changes it's value. This is all working fine and I can see the value being changed on the $scope. But, my initial max length is still being applied. Following error pops up after initial max number of chars is reached. Why?
<span class="error" data-ng-show="(searchForm.$dirty && searchForm.searchId.$error.maxlength)">Too long!</span>
This is the intended behaviour of ng-maxlength. Verified from source : https://github.com/angular/angular.js/blob/master/src/ng/directive/input.js?source=c#L523
The value is parsed only once and cached :
var maxlength = int(attr.ngMaxlength);
If you want to observe the change you need to create your own directive which uses something like
scope.$watch(attr.namespaceMaxLength,function(){
// clear old validator. Add new one.
})
After a lot of trial and error here is the directive that does what I need. Please if you have any suggestions or improvements share them, I have only 7 days of angular under my belt, and javascript is something that i have a cursory knowledge of.
(function () {
'use strict';
angular.module('commonModule')
.directive('srMaxlength', ['$window', srMaxlength]);
function srMaxlength($window) {
// Usage:
// use if you need to switch max length validation dynamically based on
// Creates:
// removes old validator for max length and creates new one
var directive = {
require: 'ngModel',
link: link,
restrict: 'A'
};
return directive;
function link(scope, element, attrs, ctrl) {
attrs.$observe("srMaxlength", function (newval) {
var maxlength = parseInt(newval, 10);
var name = "srMaxLengthValidator";
for (var i = ctrl.$parsers.length - 1; i >= 0; i--) {
if (ctrl.$parsers[i].name !== undefined && ctrl.$parsers[i].name == name) {
ctrl.$parsers.splice(i, 1);
}
}
for (var j = ctrl.$formatters.length - 1; j >= 0; j--) {
if (ctrl.$formatters[j].name !== undefined && ctrl.$formatters[j].name == name) {
ctrl.$formatters.splice(j, 1);
}
}
ctrl.$parsers.push(maxLengthValidator);
ctrl.$formatters.push(maxLengthValidator);
//name the function so we can find it always by the name
maxLengthValidator.name = name;
function maxLengthValidator(value) {
if (!ctrl.$isEmpty(value) && value.length > maxlength) {
ctrl.$setValidity('maxlength', false);
return undefined;
} else {
ctrl.$setValidity('maxlength', true);
return value;
}
}
});
}
}
})();