How to call $setValidity in directive only if required attribute exists - angularjs

I have a directive where I call this:
ngModel.$setValidity('required', isFinite(scope.inputValue) && scope.inputValue != null);
to set whether the value has been filled by the user or not. I'm pretty sure this used to only make the form invalid if my directive had required or ng-required="trueExpression" on it, but since upgrading to Angular v1.5.7 the form appears to become invalid regardless of whether the required attributes exist or not.
So how can I detect if required or ng-required="trueExpression" are on my directive so I only call this line then?
Here is my entire directive for reference:
(function () {
'use strict';
angular.module('app').directive('bigNumberInput', bigNumberInput);
bigNumberInput.$inject = [];
function bigNumberInput() {
return {
restrict: 'EA',
require: 'ngModel', // get a hold of NgModelController
transclude: true,
scope: {
label: '#'
},
templateUrl: 'app/directives/bigNumberInput.html',
link: function (scope, element, attrs, ngModel) {
//scope.inputValue = null;
ngModel.$formatters.push(function (modelValue) {
var inputValue = null;
var sizeValue = "";
if (modelValue != null) {
if (modelValue / 1000000000 >= 1.0) {
inputValue = modelValue / 1000000000;
sizeValue = "B";
} else if (modelValue / 1000000 >= 1.0) {
inputValue = modelValue / 1000000;
sizeValue = "MM";
} else if (modelValue / 1000 >= 1.0) {
inputValue = modelValue / 1000;
sizeValue = "K";
} else {
inputValue = modelValue;
sizeValue = "";
}
}
return { inputValue: inputValue, sizeValue: sizeValue };
});
ngModel.$render = function () {
scope.inputValue = ngModel.$viewValue.inputValue;
scope.sizeValue = ngModel.$viewValue.sizeValue;
};
scope.$watch('inputValue + sizeValue', function () {
ngModel.$setViewValue({
inputValue: scope.inputValue,
sizeValue: scope.sizeValue
});
ngModel.$setValidity('required', isFinite(scope.inputValue) && scope.inputValue != null);
});
ngModel.$parsers.push(function (viewValue) {
var inputValue = viewValue.inputValue;
if (inputValue != null) {
if (viewValue.sizeValue === 'K') {
inputValue = inputValue * 1000;
} else if (viewValue.sizeValue === "MM") {
inputValue = inputValue * 1000000;
} else if (viewValue.sizeValue === "B") {
inputValue = inputValue * 1000000000;
}
}
return inputValue;
});
}
};
}
}());
And here is the HTML template for it:
<div layout="row">
<md-input-container flex>
<label>{{label}}</label>
<input type="number" step="any" ng-model="inputValue"/>
<div ng-transclude></div>
</md-input-container>
<md-input-container>
<label>Type</label>
<md-select ng-model="sizeValue" md-on-open="valuationTypeOpen = true" md-on-close="valuationTypeOpen = false">
<md-option value="">{{valuationTypeOpen ? 'Verbatim (=)' : '='}}</md-option>
<md-option value="K">{{valuationTypeOpen ? 'Thousands (K)' : 'K'}}</md-option>
<md-option value="MM">{{valuationTypeOpen ? 'Millions (MM)' : 'MM'}}</md-option>
<md-option value="B">{{valuationTypeOpen ? 'Billions (B)' : 'B'}}</md-option>
</md-select>
</md-input-container>
</div>

I think I found the answer on my own. I believe it's just a matter checking if the "required" attribute returns true like this:
ngModel.$setValidity('required', !attrs.required || (isFinite(scope.inputValue) && scope.inputValue != null));
It appears to be working for hard-coded required attributes as well as using ng-required attributes.

Related

Untouching methods doesn't work in my directive

I've write a directive for textarea Html tag to submit a description to an API. I need to set this tag untouched after I submit the data. I use $scope.$setPristine() and then $scope.apply() but this doesn't work!I also tried ngModelCtrl.$setUntouched() and I got same result.
The Directive tag is as below:
<div class="col-sm-12">
<dp-text-area
dp-tabindex="11"
label="Description"
placeholder="Description"
ng-model="vm.cityModel.description">
</dp-text-area>
</div>
Here is the directive JavaScript code:
function dpTextArea($timeout) {
return {
restrict: 'E',
require: "ngModel",
scope: {
label: '#',
placeholder: '#',
externalNgModel: '=ngModel',
editDisabled: '#',
ngRequired: '=',
dpTabindex: '='
},
link(scope, elm, attr, ngModelCtrl) {
scope.safeApply = function (fn) {
var phase = this.$root.$$phase;
if (phase == '$apply' || phase == '$digest') {
if (fn && (typeof(fn) === 'function')) {
fn();
}
} else {
this.$apply(fn);
}};
scope.$watch(() => {
return scope.editDisabled;
}, (n, o) => {
// if (n == o)return;
if (scope.editDisabled === 'false') {
scope.editDisabled = false;
}
});
scope.isTextareaTouched = false;
scope.isTextareaInvalid = false;
if (scope.ngRequired)
scope.isTextareaInvalid = true;
scope.blurFunc = () => {
scope.isTextareaTouched = true;
};
//#region watch $error
scope.$watch(
function () {
let rtn = JSON.stringify(ngModelCtrl.$error);
return rtn;
},
function (n, o) {
if (n == o) return;
if (Object.keys(ngModelCtrl.$error).length == 0) {
scope.isTextareaInvalid = false;
} else {
scope.isTextareaInvalid = true;
}
});
//#endregion
},
template: require('./dpTextArea.directive.html')
}}
export default angular.module('directives.dpTextArea', [])
.directive('dpTextArea', dpTextArea)
.name;
And here is the template of the directive:
<div class="form-group" ng-class="{'has-error':isTextareaInvalid && isTextareaTouched}">
<label class="control-label">
{{label || 'description'}}
<sup class="text-danger" ng-show="ngRequired">*</sup>
</label>
<textarea rows="3" type="text"
tabindex="{{dpTabindex}}"
class="form-control"
ng-class="{'edit-disabled':editDisabled}"
ng-disabled="editDisabled"
placeholder="{{placeholder || 'description'}}"
ng-model="externalNgModel"
ng-required="ngRequired"
ng-blur="blurFunc()"
></textarea>
<small class="help-block" ng-show="isTextareaInvalid && isTextareaTouched">this field is requred.</small>
I appreciate any help.

about angularJS directives

I write a directive called ValidateChineseDirective.
define(function(){
'use strict';
return function(module){
module.directive('validateChinese',function(){
return {
restrict:'A',
require:'ngModel',
link:function(scope,ele,attr,ngModel){
if (!ngModel) return;
var maxlength = -1;
attr.$observe('validateChinese', function(value) {
var intVal = parseInt(value,10);
maxlength = isNaN(intVal) ? -1 : intVal;
ngModel.$validate();
});
ngModel.$parsers.push(function(viewValue){
var valueArray = viewValue.split("");
var reg = /[\u4E00-\u9FA5\uF900-\uFA2D]/;
var len=0;
for(var i=0;i<valueArray.length;i++){
len += reg.test(valueArray[i])?4:1;
}
if(len<=maxlength){
ngModel.$setValidity('validateChinese',true);
}else{
ngModel.$setValidity('validateChinese',false);
}
return viewValue;
});
}
}
})
}
})
html:
<input type="text" name="approvedDocNo" validate_chinese="4" ng-model="fundMaintenanceVM.editData.approvedDocNo" class="form-control">
the reg was used for matching chinese.
I found that whether input space at the begin of the input box or at the end of it.
ngModel.$parsers.push didn't trigger until type a character.
furthermore,when ngModel.$parsers.push triggered, viewValue didn't contain the space which is at the end of this input box or at the end of it.Does somebody can help me ,thx.
add ng-trim="false" to the input element which used your directive.
The reason is that: Angular sets ng-trim to true by default, which trims white space in input boxes, and leads no change with ngModel.
angular.module("app", []).directive('validateChinese', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, ele, attr, ngModel) {
if (!ngModel) return;
var maxlength = -1;
attr.$observe('validateChinese', function(value) {
var intVal = parseInt(value, 10);
maxlength = isNaN(intVal) ? -1 : intVal;
ngModel.$validate();
});
ngModel.$parsers.push(function(viewValue) {
var valueArray = viewValue.split("");
var reg = /[\u4E00-\u9FA5\uF900-\uFA2D]/;
var len = 0;
for (var i = 0; i < valueArray.length; i++) {
len += reg.test(valueArray[i]) ? 4 : 1;
}
if (len <= maxlength) {
ngModel.$setValidity('validateChinese', true);
} else {
ngModel.$setValidity('validateChinese', false);
}
console.log('ngModel.$parsers.push fired.');
return viewValue;
});
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.4/angular.min.js"></script>
<div ng-app="app">
<input type="text" name="approvedDocNo" validate_chinese="4" ng-model="approvedDocNo" ng-trim="false" class="form-control">
{{approvedDocNo}}
</div>

angularjs - ngpattern and custom validation is both displayed

I have a min and max directive that I've created which checks if an input is between a range. I also have an ng-pattern validation. I'm using ng-messages to display my validation. I have an issue where even though user has entered in the correct pattern, the validation message for "pattern" is still displaying. I only would like to display the validation that the range is outside the range. Here is the html
<form name="fee">
<input type="text" name="fee_classi" ng-model="main.fee.I"
ng-pattern="/^[0-1](\.\d{0,2}){0,1}$/"
my-range="1,1.75"/>
<div role="alert" class="validation-errors"
ng-if="fee.fee_classi.$invalid && fee.fee_classi.$dirty"
ng-messages="fee.fee_classi.$error">
<p ng-message="range">Range should be between 1 to 1.75</p>
<p ng-message="pattern">Format must be 0.00</p>
</div>
</form>
Here is the directive
app.directive('myRange', myRange);
function myRange() {
var directive = {
bindToController: true,
controller: myRangeCtrl,
controllerAs: 'vm',
// link: link,
restrict: 'A',
scope: {},
require: {
ngModelCtrl: 'ngModel'
}
};
return directive;
}
myRangeCtrl.$inject = ['$element', '$attrs'];
function myRangeCtrl($element, $attrs) {
var vm = this;
vm.min = 0; //default
vm.max = 0; //default
console.clear();
console.log(vm.ngModelCtrl);
var inRange = false;
var rangeVal = $attrs.myRange.split(',');
var userInput;
console.log(rangeVal);
vm.min = JSON.parse(rangeVal[0]);
vm.max = JSON.parse(rangeVal[1]);
$element.on('keypress', function(e) {
console.log(e);
console.log(vm.ngModelCtrl);
//if the pattern is valid then lets check if the user has the proper range
if (vm.ngModelCtrl.$valid) {
vm.ngModelCtrl.$validators.range = function(modelValue, viewValue) {
console.log('modelValue = ' + modelValue);
inRange = _.inRange(modelValue, vm.min, vm.max);
//check if modelValue can be converted to a number with isNaN function
if (isNaN(modelValue)) {
console.error('-VAlue is invalid');
return false;
}
if (angular.isDefined(modelValue) &&
modelValue[modelValue.length - 1] !== '.' &&
modelValue !== '') {
// console.log('modelValue = '+modelValue);
userInput = JSON.parse(modelValue);
if (inRange || userInput === vm.max) {
console.info('VAlue is valid');
//value entered is invalid
return true;
} else {
console.error('VAlue is invalid');
//value entered is valid
return false;
}
}
if (angular.isUndefined(modelValue)) {
return true;
}
//lets do a regex test first
};
}
});
Here is the plunkr
Look at this example: https://docs.angularjs.org/api/ng/input/input%5Brange%5D
You may need to tweak it a bit to fit for your need.

Parent scope update by angularjs datepicker directive

I am developing a datePicker directive comprising 3 x selects (views/datetime.html)
<select class="form-control input-group-sm w75 float-left"
ng-model="mth"
ng-options="x for x in ['Jan','Feb','Mar','Apr','May','Jun']">
</select>
<select class="form-control input-group-sm w75 float-left"
ng-model="day"
ng-options="x for x in [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]">
</select>
<select class="form-control input-group-sm w75"
ng-model="year"
ng-options="x for x in [2014,2015,2016,2017,2018]">
</select>
The directive can be used one or more time in each html view (startdate, enddate, etc)
<div class="input-group-sm" date-picker ng-model="startdate"></div>
My directive is coded as follows:
App.directive('datePicker', function () {
var date = {};
var objLink = {
restrict: 'A',
templateUrl: 'views/datetime.html',
scope: {
ngModel: '=',
},
link: function($scope, element, attr) {
$scope.$watch("mth", function(value) {
if ( typeof value != 'undefined' ) {
date.mth = value;
updateTarget($scope, attr);
}
});
$scope.$watch("day", function(value) {
if ( typeof value != 'undefined' ) {
date.day = value;
updateTarget($scope, attr);
}
});
$scope.$watch("year", function(value) {
if ( typeof value != 'undefined' ) {
date.year = value;
updateTarget($scope, attr);
}
});
}
};
return objLink;
function updateTarget( scope, attr ) {
var d = date.mth+'-'+date.day+'-'+date.year;
scope[attr.date] = d;
}
});
My issue is that function UpdateTarget() does NOT update the $scope.startdate in the controller.
Any ideas...anyone? Thanks in advance.
scope[attr.date] = d;
Here attr.date is undefined. To update the $scope.startdate in the controller, you need to pass attr.ngModel as stated below
scope[attr.ngModel] = d;
...Worked it all out myself! Thx for any feedback.
App.directive('datePicker', function () {
var mths = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var dirLink = {
restrict: 'A',
templateUrl: 'views/datetime.html',
scope: {
data : '='
},
link: function($scope, element, attr) {
// watch bound data item for change
// - ajax load delay from view render
$scope.$watch("data", function(value) {
if ( typeof $scope.data == 'undefined' ) {
return;
}
// initialise view controls
if ( typeof $scope.mth == 'undefined' ) {
var a = $scope.data.split(' ');
var dt = a[0].split('-');
$scope.mth = mths[dt[1]-1];
$scope.year = dt[0];
$scope.day = dt[2];
}
});
// watch view controls
$scope.$watch("mth", function(value) {
if ( typeof value != 'undefined' ) {
var mth = padl(mths.indexOf(value)+1);
updateTarget($scope, 'mth', mth);
}
});
$scope.$watch("day", function(value) {
if ( typeof value != 'undefined' ) {
updateTarget($scope, 'day', value);
}
});
$scope.$watch("year", function(value) {
if ( typeof value != 'undefined' ) {
updateTarget($scope, 'year', value);
}
});
}
};
return dirLink;
function updateTarget( scope, seg, val ) {
// init date if empty
if ( scope.data.length < 8 ) {
var d = new Date();
var dt = d.getYear()+'-'+padl(d.getMonth())+'-'+padl(d.getDate());
scope.data = dt;
}
// split existing data
var a = scope.data.split(' ');
var dt = a[0].split('-');
// change selected segment
var d = ['year','mth','day'];
dt[d.indexOf(seg)] = val;
// reassemble date
var d = dt[0]+'-'+dt[1]+'-'+dt[2];
scope.data = d;
}
function padl( n ) {
return ("0"+n).slice(-2);
}
});

How to allow only a number (digits and decimal point) to be typed in an input?

What is the way to allow only a valid number typed into a textbox?
For example, user can type in "1.25", but cannot type in "1.a" or "1..". When user try to type in the next character which will make it an invalid number, they cannot type it in.
I wrote a working CodePen example to demonstrate a great way of filtering numeric user input. The directive currently only allows positive integers, but the regex can easily be updated to support any desired numeric format.
My directive is easy to use:
<input type="text" ng-model="employee.age" valid-number />
The directive is very easy to understand:
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope) {
});
app.directive('validNumber', function() {
return {
require: '?ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
if(!ngModelCtrl) {
return;
}
ngModelCtrl.$parsers.push(function(val) {
if (angular.isUndefined(val)) {
var val = '';
}
var clean = val.replace( /[^0-9]+/g, '');
if (val !== clean) {
ngModelCtrl.$setViewValue(clean);
ngModelCtrl.$render();
}
return clean;
});
element.bind('keypress', function(event) {
if(event.keyCode === 32) {
event.preventDefault();
}
});
}
};
});
I want to emphasize that keeping model references out of the directive is important.
I hope you find this helpful.
Big thanks to Sean Christe and Chris Grimes for introducing me to the ngModelController
You could try this directive to stop any invalid characters from being entered into an input field. (Update: this relies on the directive having explicit knowledge of the model, which is not ideal for reusability, see below for a re-usable example)
app.directive('isNumber', function () {
return {
require: 'ngModel',
link: function (scope) {
scope.$watch('wks.number', function(newValue,oldValue) {
var arr = String(newValue).split("");
if (arr.length === 0) return;
if (arr.length === 1 && (arr[0] == '-' || arr[0] === '.' )) return;
if (arr.length === 2 && newValue === '-.') return;
if (isNaN(newValue)) {
scope.wks.number = oldValue;
}
});
}
};
});
It also accounts for these scenarios:
Going from a non-empty valid string to an empty string
Negative values
Negative decimal values
I have created a jsFiddle here so you can see how it works.
UPDATE
Following Adam Thomas' feedback regarding not including model references directly inside a directive (which I also believe is the best approach) I have updated my jsFiddle to provide a method which does not rely on this.
The directive makes use of bi-directional binding of local scope to parent scope. The changes made to variables inside the directive will be reflected in the parent scope, and vice versa.
HTML:
<form ng-app="myapp" name="myform" novalidate>
<div ng-controller="Ctrl">
<number-only-input input-value="wks.number" input-name="wks.name"/>
</div>
</form>
Angular code:
var app = angular.module('myapp', []);
app.controller('Ctrl', function($scope) {
$scope.wks = {number: 1, name: 'testing'};
});
app.directive('numberOnlyInput', function () {
return {
restrict: 'EA',
template: '<input name="{{inputName}}" ng-model="inputValue" />',
scope: {
inputValue: '=',
inputName: '='
},
link: function (scope) {
scope.$watch('inputValue', function(newValue,oldValue) {
var arr = String(newValue).split("");
if (arr.length === 0) return;
if (arr.length === 1 && (arr[0] == '-' || arr[0] === '.' )) return;
if (arr.length === 2 && newValue === '-.') return;
if (isNaN(newValue)) {
scope.inputValue = oldValue;
}
});
}
};
});
First of all Big thanks to Adam thomas
I used the same Adam's logic for this with a small modification to accept the decimal values.
Note: This will allow digits with only 2 decimal values
Here is my Working Example
HTML
<input type="text" ng-model="salary" valid-number />
Javascript
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope) {
});
app.directive('validNumber', function() {
return {
require: '?ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
if(!ngModelCtrl) {
return;
}
ngModelCtrl.$parsers.push(function(val) {
if (angular.isUndefined(val)) {
var val = '';
}
var clean = val.replace(/[^0-9\.]/g, '');
var decimalCheck = clean.split('.');
if(!angular.isUndefined(decimalCheck[1])) {
decimalCheck[1] = decimalCheck[1].slice(0,2);
clean =decimalCheck[0] + '.' + decimalCheck[1];
}
if (val !== clean) {
ngModelCtrl.$setViewValue(clean);
ngModelCtrl.$render();
}
return clean;
});
element.bind('keypress', function(event) {
if(event.keyCode === 32) {
event.preventDefault();
}
});
}
};
});
Use the step tag to set the minimum changeable value to some decimal number:
e.g.
step="0.01"
<input type="number" step="0.01" min="0" class="form-control"
name="form_name" id="your_id" placeholder="Please Input a decimal number" required>
There is some documentation on it here:
http://blog.isotoma.com/2012/03/html5-input-typenumber-and-decimalsfloats-in-chrome/
DEMO - - jsFiddle
Directive
.directive('onlyNum', function() {
return function(scope, element, attrs) {
var keyCode = [8,9,37,39,48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105,110];
element.bind("keydown", function(event) {
console.log($.inArray(event.which,keyCode));
if($.inArray(event.which,keyCode) == -1) {
scope.$apply(function(){
scope.$eval(attrs.onlyNum);
event.preventDefault();
});
event.preventDefault();
}
});
};
});
HTML
<input type="number" only-num>
Note : Do not forget include jQuery with angular js
You could easily use the ng-pattern.
ng-pattern="/^[1-9][0-9]{0,2}(?:,?[0-9]{3}){0,3}(?:\.[0-9]{1,2})?$/"
There is an input number directive which I belive can do just what you want.
<input type="number"
ng-model="{string}"
[name="{string}"]
[min="{string}"]
[max="{string}"]
[required]
[ng-required="{string}"]
[ng-minlength="{number}"]
[ng-maxlength="{number}"]
[ng-pattern="{string}"]
[ng-change="{string}"]>
the official doc is here: http://docs.angularjs.org/api/ng.directive:input.number
HTML
<input type="text" name="number" only-digits>
// Just type 123
.directive('onlyDigits', function () {
return {
require: 'ngModel',
restrict: 'A',
link: function (scope, element, attr, ctrl) {
function inputValue(val) {
if (val) {
var digits = val.replace(/[^0-9]/g, '');
if (digits !== val) {
ctrl.$setViewValue(digits);
ctrl.$render();
}
return parseInt(digits,10);
}
return undefined;
}
ctrl.$parsers.push(inputValue);
}
};
// type: 123 or 123.45
.directive('onlyDigits', function () {
return {
require: 'ngModel',
restrict: 'A',
link: function (scope, element, attr, ctrl) {
function inputValue(val) {
if (val) {
var digits = val.replace(/[^0-9.]/g, '');
if (digits !== val) {
ctrl.$setViewValue(digits);
ctrl.$render();
}
return parseFloat(digits);
}
return undefined;
}
ctrl.$parsers.push(inputValue);
}
};
I wanted a directive that could be limited in range by min and max attributes like so:
<input type="text" integer min="1" max="10" />
so I wrote the following:
.directive('integer', function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, elem, attr, ngModel) {
if (!ngModel)
return;
function isValid(val) {
if (val === "")
return true;
var asInt = parseInt(val, 10);
if (asInt === NaN || asInt.toString() !== val) {
return false;
}
var min = parseInt(attr.min);
if (min !== NaN && asInt < min) {
return false;
}
var max = parseInt(attr.max);
if (max !== NaN && max < asInt) {
return false;
}
return true;
}
var prev = scope.$eval(attr.ngModel);
ngModel.$parsers.push(function (val) {
// short-circuit infinite loop
if (val === prev)
return val;
if (!isValid(val)) {
ngModel.$setViewValue(prev);
ngModel.$render();
return prev;
}
prev = val;
return val;
});
}
};
});
Here's my really quick-n-dirty one:
<!-- HTML file -->
<html ng-app="num">
<head></head>
<body ng-controller="numCtrl">
<form class="digits" name="digits" ng-submit="getGrades()" novalidate >
<input type="text" placeholder="digits here plz" name="nums" ng-model="nums" required ng-pattern="/^(\d)+$/" />
<p class="alert" ng-show="digits.nums.$error.pattern">Numbers only, please.</p>
<br>
<input type="text" placeholder="txt here plz" name="alpha" ng-model="alpha" required ng-pattern="/^(\D)+$/" />
<p class="alert" ng-show="digits.alpha.$error.pattern">Text only, please.</p>
<br>
<input class="btn" type="submit" value="Do it!" ng-disabled="!digits.$valid" />
</form>
</body>
</html>
// Javascript file
var app = angular.module('num', ['ngResource']);
app.controller('numCtrl', function($scope, $http){
$scope.digits = {};
});
This requires you include the angular-resource library for persistent bindings to the fields for validation purposes.
Working example here
Works like a champ in 1.2.0-rc.3+. Modify the regex and you should be all set. Perhaps something like /^(\d|\.)+$/ ? As always, validate server-side when you're done.
This one seems the easiest to me:
http://jsfiddle.net/thomporter/DwKZh/
(Code is not mine, I accidentally stumbled upon it)
angular.module('myApp', []).directive('numbersOnly', function(){
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
// this next if is necessary for when using ng-required on your input.
// In such cases, when a letter is typed first, this parser will be called
// again, and the 2nd time, the value will be undefined
if (inputValue == undefined) return ''
var transformedInput = inputValue.replace(/[^0-9]/g, '');
if (transformedInput!=inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});
I modified Alan's answer above to restrict the number to the specified min/max. If you enter a number outside the range, it will set the min or max value after 1500ms. If you clear the field completely, it will not set anything.
HTML:
<input type="text" ng-model="employee.age" min="18" max="99" valid-number />
Javascript:
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope) {});
app.directive('validNumber', function($timeout) {
return {
require: '?ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
if (!ngModelCtrl) {
return;
}
var min = +attrs.min;
var max = +attrs.max;
var lastValue = null;
var lastTimeout = null;
var delay = 1500;
ngModelCtrl.$parsers.push(function(val) {
if (angular.isUndefined(val)) {
val = '';
}
if (lastTimeout) {
$timeout.cancel(lastTimeout);
}
if (!lastValue) {
lastValue = ngModelCtrl.$modelValue;
}
if (val.length) {
var value = +val;
var cleaned = val.replace( /[^0-9]+/g, '');
// This has no non-numeric characters
if (val.length === cleaned.length) {
var clean = +cleaned;
if (clean < min) {
clean = min;
} else if (clean > max) {
clean = max;
}
if (value !== clean || value !== lastValue) {
lastTimeout = $timeout(function () {
lastValue = clean;
ngModelCtrl.$setViewValue(clean);
ngModelCtrl.$render();
}, delay);
}
// This has non-numeric characters, filter them out
} else {
ngModelCtrl.$setViewValue(lastValue);
ngModelCtrl.$render();
}
}
return lastValue;
});
element.bind('keypress', function(event) {
if (event.keyCode === 32) {
event.preventDefault();
}
});
element.on('$destroy', function () {
element.unbind('keypress');
});
}
};
});
I had a similar problem and update the input[type="number"] example on angular docs for works with decimals precision and I'm using this approach to solve it.
PS: A quick reminder is that the browsers supports the characters 'e' and 'E' in the input[type="number"], because that the keypress event is required.
angular.module('numfmt-error-module', [])
.directive('numbersOnly', function() {
return {
require: 'ngModel',
scope: {
precision: '#'
},
link: function(scope, element, attrs, modelCtrl) {
var currencyDigitPrecision = scope.precision;
var currencyDigitLengthIsInvalid = function(inputValue) {
return countDecimalLength(inputValue) > currencyDigitPrecision;
};
var parseNumber = function(inputValue) {
if (!inputValue) return null;
inputValue.toString().match(/-?(\d+|\d+.\d+|.\d+)([eE][-+]?\d+)?/g).join('');
var precisionNumber = Math.round(inputValue.toString() * 100) % 100;
if (!!currencyDigitPrecision && currencyDigitLengthIsInvalid(inputValue)) {
inputValue = inputValue.toFixed(currencyDigitPrecision);
modelCtrl.$viewValue = inputValue;
}
return inputValue;
};
var countDecimalLength = function (number) {
var str = '' + number;
var index = str.indexOf('.');
if (index >= 0) {
return str.length - index - 1;
} else {
return 0;
}
};
element.on('keypress', function(evt) {
var charCode, isACommaEventKeycode, isADotEventKeycode, isANumberEventKeycode;
charCode = String.fromCharCode(evt.which || event.keyCode);
isANumberEventKeycode = '0123456789'.indexOf(charCode) !== -1;
isACommaEventKeycode = charCode === ',';
isADotEventKeycode = charCode === '.';
var forceRenderComponent = false;
if (modelCtrl.$viewValue != null && !!currencyDigitPrecision) {
forceRenderComponent = currencyDigitLengthIsInvalid(modelCtrl.$viewValue);
}
var isAnAcceptedCase = isANumberEventKeycode || isACommaEventKeycode || isADotEventKeycode;
if (!isAnAcceptedCase) {
evt.preventDefault();
}
if (forceRenderComponent) {
modelCtrl.$render(modelCtrl.$viewValue);
}
return isAnAcceptedCase;
});
modelCtrl.$render = function(inputValue) {
return element.val(parseNumber(inputValue));
};
modelCtrl.$parsers.push(function(inputValue) {
if (!inputValue) {
return inputValue;
}
var transformedInput;
modelCtrl.$setValidity('number', true);
transformedInput = parseNumber(inputValue);
if (transformedInput !== inputValue) {
modelCtrl.$viewValue = transformedInput;
modelCtrl.$commitViewValue();
modelCtrl.$render(transformedInput);
}
return transformedInput;
});
}
};
});
And in your html you can use this approach
<input
type="number"
numbers-only
precision="2"
ng-model="model.value"
step="0.10" />
Here is the plunker with this snippet
Expanding from gordy's answer:
Good job btw. But it also allowed + in the front. This will remove it.
scope.$watch('inputValue', function (newValue, oldValue) {
var arr = String(newValue).split("");
if (arr.length === 0) return;
if (arr.length === 1 && (arr[0] == '-' || arr[0] === '.')) return;
if (arr.length === 2 && newValue === '-.') return;
if (isNaN(newValue)) {
scope.inputValue = oldValue;
}
if (arr.length > 0) {
if (arr[0] === "+") {
scope.inputValue = oldValue;
}
}
});
Here is a derivative that will also block the decimal point to be entered twice
HTML
<input tabindex="1" type="text" placeholder="" name="salary" id="salary" data-ng-model="salary" numbers-only="numbers-only" required="required">
Angular
var app = angular.module("myApp", []);
app.directive('numbersOnly', function() {
return {
require : 'ngModel', link : function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function(inputValue) {
if (inputValue == undefined) {
return ''; //If value is required
}
// Regular expression for everything but [.] and [1 - 10] (Replace all)
var transformedInput = inputValue.replace(/[a-z!##$%^&*()_+\-=\[\]{};':"\\|,<>\/?]/g, '');
// Now to prevent duplicates of decimal point
var arr = transformedInput.split('');
count = 0; //decimal counter
for ( var i = 0; i < arr.length; i++) {
if (arr[i] == '.') {
count++; // how many do we have? increment
}
}
// if we have more than 1 decimal point, delete and leave only one at the end
while (count > 1) {
for ( var i = 0; i < arr.length; i++) {
if (arr[i] == '.') {
arr[i] = '';
count = 0;
break;
}
}
}
// convert the array back to string by relacing the commas
transformedInput = arr.toString().replace(/,/g, '');
if (transformedInput != inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});
Extending Adam Thomas answer you can easily make this directive more generic by adding input argument with custom regexp:
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope) {
});
app.directive('validInput', function() {
return {
require: '?ngModel',
scope: {
"inputPattern": '#'
},
link: function(scope, element, attrs, ngModelCtrl) {
var regexp = null;
if (scope.inputPattern !== undefined) {
regexp = new RegExp(scope.inputPattern, "g");
}
if(!ngModelCtrl) {
return;
}
ngModelCtrl.$parsers.push(function(val) {
if (regexp) {
var clean = val.replace(regexp, '');
if (val !== clean) {
ngModelCtrl.$setViewValue(clean);
ngModelCtrl.$render();
}
return clean;
}
else {
return val;
}
});
element.bind('keypress', function(event) {
if(event.keyCode === 32) {
event.preventDefault();
}
});
}
}});
HTML
<input type="text" ng-model="employee.age" valid-input
input-pattern="[^0-9]+" placeholder="Enter an age" />
</label>
Live on CodePen
Please check out my component that will help you to allow only a particular data type. Currently supporting integer, decimal, string and time(HH:MM).
string - String is allowed with optional max length
integer - Integer only allowed with optional max value
decimal - Decimal only allowed with optional decimal points and max value (by default 2 decimal points)
time - 24 hr Time format(HH:MM) only allowed
https://github.com/ksnimmy/txDataType
Hope that helps.
DECIMAL
directive('decimal', function() {
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, element, attr, ctrl) {
function inputValue(val) {
if (val) {
var digits = val.replace(/[^0-9.]/g, '');
if (digits.split('.').length > 2) {
digits = digits.substring(0, digits.length - 1);
}
if (digits !== val) {
ctrl.$setViewValue(digits);
ctrl.$render();
}
return parseFloat(digits);
}
return "";
}
ctrl.$parsers.push(inputValue);
}
};
});
DIGITS
directive('entero', function() {
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, element, attr, ctrl) {
function inputValue(val) {
if (val) {
var value = val + ''; //convert to string
var digits = value.replace(/[^0-9]/g, '');
if (digits !== value) {
ctrl.$setViewValue(digits);
ctrl.$render();
}
return parseInt(digits);
}
return "";
}
ctrl.$parsers.push(inputValue);
}
};
});
angular directives for validate numbers

Resources