I'm building an Angular directive which allows the user to enter a North American phone number in a variety of common formats (such as "1(301) 797-1483" or "301.797.1483"), but stores it internally as a normalized number in the form "3017971483".
I have the $parser working: it strips out all non-numeric characters as the user types, and strips off the first character if it's a "1". However, I'd like to add validation to this, such that:
If the $parser can't translate the current $viewValue to a valid normalized number (i.e., because it doesn't contain enough digits, or contains unacceptable junk characters), then:
$modelValue will be empty; and
the ModelController's $valid / $invalid flags will be set appropriately, and its $error.pattern property will be set to true. (I guess it doesn't have to be pattern, but that seems like the sensible one to use.)
This is basically how Angular handles default validation via attributes such as pattern and required. But I'm having a devil of a time figuring out how to make this work with my directive.
My code is below; you can also view this on CodePen. Here's my HTML:
<div ng-app="DemoApp">
<form ng-controller="MainController" name="phoneForm">
<input phone-input type="tel" name="phone" ng-model="phone">
<p ng-show="phoneForm.phone.$error.pattern">Invalid format!</p>
<p>$viewValue is: {{ phoneForm.phone.$viewValue }}</p>
<p>$modelValue is: {{ phone }}</p>
</form>
</div>
And here's my JavaScript:
angular
.module( 'DemoApp', [] )
.controller( 'MainController', [ '$scope', function( $scope ) {
$scope.phone = '';
} ] )
.directive( 'phoneInput', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function( scope, $el, attrs, ngModel ) {
// convert human-friendly input to normalized format for internal storage
ngModel.$parsers.push( function( value ) {
return normalizePhone( value );
} );
function normalizePhone( phone ) {
// remove all non-numeric characters
phone = phone.replace( /[^0-9]/g, '' );
// if the first character is a "1", remove it
if ( phone[0] === '1' ) {
phone = phone.substr( 1 );
}
return phone;
}
}
};
} );
If you play with the form, you'll notice that the "Invalid format!" message is never shown. I don't expect this code to show it - that's what I'm trying to figure out how to do cleanly.
I already have a solid regex for determining whether the $viewValue can be translated into a valid number - e.g., "1(301) 797-1483" passes the regex, but "1(301) 797-148" does not. What I'm trying to figure out is where/when/how to perform this check, and where/when/how to flag the model as invalid.
Simply adding pattern="^regex_goes_here$" to my <input> doesn't work - that checks the format of the $modelValue after normalization, which is not what I want.
I've tried a bunch of different things, but nothing quite behaves the way I want, and I'm out of ideas at this point.
What is the "right" way to combine a $parser with a $validator? Surely there's an established pattern for this.
A method passed to $validators receives as parameters both $modelValue and $viewValue, which means that you can actually validate by both of them (pen - enter some letters):
ngModel.$validators.pattern = function($modelValue, $viewValue) {
var pattern = /^\d*$/; // whatever your pattern is
return pattern.test($viewValue);
};
Related
I coded an angular directive for inhibiting typing from inputs by specifying a regex. In that directive I indicate a regex that will be used for allow the input data. Conceptually, it works fine, but there are two bugs in this solution:
In the first Plunker example the input must allow only numbers or numbers followed by a dot [.], or numbers followed by a dot followed by numbers with no more than four digits.
If I type a value '1.1111' and after that I go to the first digit and so type another digit (in order to get a value as '11.1111') , nothing happening. The bug is in the fact I use the expression elem.val() + event.key on my regex validator. I do not know how to get the whole
current value for a input on a keypress event;
The second one is the fact that some characters (grave, acute, tilde, circumflex) are being allowed on typing (press one of them more than once), althought the regex does not allow them.
What changes do I need to make in my code in order to get an effective type restriction by regex?
<html ng-app="app">
<head>
<script data-require="angularjs#1.6.4" data-semver="1.6.4" src="https://code.angularjs.org/1.6.4/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<h1>Restrict typing by RegExp</h1>
PATTERN 1 (^\d+$|^\d+[.]$|^\d+[.]\d{1,4}$) <input type="text" allow-typing="^\d+$|^\d+[.]$|^\d+[.]\d{1,4}$"/><br>
ONLY NUMBERS <input type="text" allow-typing="^[0-9]+$"/><br>
ONLY STRINGS <input type="text" allow-typing="^[a-zA-Z]+$"/>
</body>
</html>
Directive
angular.module('app', []).directive('allowTyping', function() {
return {
restrict: 'A',
link: function(scope, elem, attrs, ctrl) {
var regex = attrs.allowTyping;
elem.bind('keypress', function(event) {
var input = elem.val() + event.key;
var validator = new RegExp(regex);
if(!validator.test(input)) {
event.preventDefault();
return false;
}
});
}
};
});
If this were my code, I'd change tactics entirely: I would listen for input events instead of trying to micromanage the user interactions with the field.
The approach you are taking, in general, has problems. The biggest one is that keypress won't be emitted for all changes to the field. Notably,
It is not triggered by DELETE and BACKSPACE keys.
Input methods can bypass it. When you entered diacritics as diacritics, your code was not registering the change. In general, if the user is using an input method, there is no guarantee that each new character added to the field will result in a keypress event. It depends on the method the user has chosen.
keypress does not help when the user cuts from the field or pastes into the field.
You could add code to try to handle all the cases above, but it would get complex quick. You've already run into an issue with elem.val() + event.key because the keypress may not always be about a character inserted at the end of the field. The user may have moved the caret so you have to keep track of caret position. One comment suggested listening to keyup but that does not help with input methods or paste/cut events.
In contrast, the input event is generated when the value of the field changes, as the changes occur. All cases above are taken care of. This, for instance, would work:
elem.bind('input', function(event) {
var validator = new RegExp(regex);
elem.css("background-color", !validator.test(elem.val()) ? "red" : null);
});
This is a minimal illustration that you could plop into your fiddle to replace your current event handler. In a real application, I'd give the user a verbose error message rather than just change the color of the field and I'd create validator just once, outside the event handler, but this gives you the idea.
(There's also a change event but you do no want to use that. For text fields, it is generated when the focus leaves the field, which is much too late.)
See Plnkr Fixed as per your approach:
The explanation of why and the changes are explained below.
Side note: I would not implement it this way (use ngModel with $parsers and $formatters, e.g. https://stackoverflow.com/a/15090867/2103767) - implementing that is beyond the scope of your question. However I found a full implementation by regexValidate by Ben Lesh which will fit your problem domain:-
If I type a value '1.1111' and after that I go to the first digit and so type another digit (in order to get a value as '11.1111') , nothing happening.
because in your code below
var input = elem.val() + event.key;
you are assuming that the event.key is always appended at the end.
So how to get the position of the correct position and validate the the reconstructed string ? You can use an undocumented event.target.selectionStart property. Note even though you are not selecting anything you will have this populated (IE 11 and other browsers). See Plnkr Fixed
The second one is the fact that some characters (grave, acute, tilde, circumflex) are being allowed on typing (press one of them more than once), althought the regex does not allow them.
Fixed the regex - correct one below:
^[0-9]*(?:\.[0-9]{0,4})?$
So the whole thing looks as below
link: function(scope, elem, attrs, ctrl) {
var regex = attrs.allowTyping;
elem.bind('keypress', function(event) {
var pos = event.target.selectionStart;
var oldViewValue = elem.val();
var input = newViewValue(oldViewValue, pos, event.key);
console.log(input);
var validator = new RegExp(regex);
if (!validator.test(input)) {
event.preventDefault();
return false;
}
});
function newViewValue(oldViewValue, pos, key) {
if (!oldViewValue) return key;
return [oldViewValue.slice(0, pos), key, oldViewValue.slice(pos)].join('');
}
}
You specified 4 different patterns 3 different pattens in your regex separated by an alteration sign: ^\d+$|^\d+[.]$|^\d+[.]\d{1,4}$ - this will not fulfill the criteria of input must allow only numbers followed by a dot [.], followed by a number with no more than four digits. The bug "where nothing happens" occurs because the variable you are checking against is not what you think it is, check the screenshot on how you can inspect it, and what it is:
Can not reproduce.
You can change the event to keyup, so the test would run after every additional character is added.
It means you need to save the last valid input, so if the user tries to insert a character that'll turn the string invalid, the test will restore the last valid value.
Hence, the updated directive:
angular.module('app', [])
.directive('allowTyping', function() {
return {
restrict : 'A',
link : function(scope, elem, attrs, ctrl) {
var regex = attrs.allowTyping;
var lastInputValue = "";
elem.bind('keyup', function(event) {
var input = elem.val();
var validator = new RegExp(regex);
if (!validator.test(input))
// Restore last valid input
elem.val(lastInputValue).trigger('input');
else
// Update last valid input
lastInputValue = input;
});
}
};
});
I've got a scenario whereby I have to detect if certain fields in an Angular form are valid and dirty.
I am currently doing this using ng-class which works perfectly. However, I am ending up with a massive expression which looks really messy and sloppy in the html. Below is an example:
data-ng-class="{'component-is-valid' :
form.firstName.$valid && form.firstName.$dirty && form.lastName.$valid && form.lastName.$dirty && form.emailAddress.$valid && form.emailAddress.$dirty && form.mobileNumber.$valid && form.mobileNumber.$dirty}"
As you can see, this is quite long.
Is there anyway I can extract this so that I retain the flexibility of ng-class but also free up my DOM?
Make a function on your scope that accepts your form object or input fields and returns the boolean you're describing above: ng-class="{'component-is-valid': checkValidity(form)}"
You can check the whole form validation in one hit with $ctrl.form.$valid instead of checking all, as Keegan G correctly states.
That said, there can be cases where your ngClass logic get's quite large and unreadable.
An alternative approach I often adopt is to move all logic to the controller. e.g.
Template:
<div ng-class="$ctrl.componentClasses()"></div>
Controller:
controller: function() {
var vm = this;
vm.isValid = function() {
// do all your checking here, ultimately it should return a bool
return [Boolean];
}
vm.componentClasses = function() {
return {
'my-class-name': vm.isValid()
}
}
}
The application I'm building has an option for Users to change the unit distances between kilometers and miles.
I've build a small filter to convert those distances:
app.filter('distance', function() {
return function(input, scope) {
var distanceName = (scope.units.distance === 'km') ? 'km' : 'ml';
// scope.units.value is 1000 by default and 621 if miles are selected.
return (input / scope.units.value).toFixed(2) + distanceName;
};
});
In my template I use it simply like that:
{{ point.distance | distance }}
The issue is when the $scope.units.value change the filter do not update the value, I should re run the filter in someway... Even if I expect it to be done by Angular, but it doesn't.
When the value change the digest is started so if I force it with $scope.$apply() it fire an error.
How can I solve it, what I'm missing for it to work?
The second (and consequent) input arguments to a filter are specified using the colon : operators.
Right now you're not specifying a second argument to your filter.
points.distance is the input argument, arguments specified after colons are the rest of the possible parameters.
So in your case units.distance maps to scope on your filter, which is a confusing name, consider changing it to measurement or something like that
For your filter to work you also need units.value. Add an additional parameter to your filter return function(input, measurement, value) ... and use it like so
{{ point.distance | distance:units.distance:units.value }}
EDIT: Like #charlietfl mentioned, a simpler solution would probably be:
return function(input, measurementConfig) ...
Usage:
{{ point.distance | distance:units }}
I need to dynamically change a mask.
So I'm making this directive to handle it:
link: function($scope, $element, $attrs, ngModel) {
$scope.$watch($attrs.ngModel, function(value) {
if (value.length > 4) {
$element.attr('mask', '9999 9999');
}
else {
$element.attr('mask', '99999999');
}
});
}
The mask is being applied, I'm checking the DOM, but there's no effect whatsoever.
What I am missing here?
Can you do that logic in the dom instead of the link? Modyfing the attr probably won't do anything as it's already been parsed and it might not be watching it.
ng-model="maskModel" mask="{{ maskModel.length > 4 ? '9999 9999' : '99999999' }}"
I know this isn't what you are asking but it may help others coming here. A good alternative is to define an optional character. To do that just add an '?' after the character you want to be optional:
mask="9?9999-9999"
This is great for inputs like Brazilian phone numbers, which can have both 8 or 9 characters.
Use attrs.$observe(..) instead of $scope.$watch (..).
I am having trouble getting a filter to work on a number/text input.
<input type="number" class="text-center" ng-model="redeem.redemption.Amount | number: 2">
This throws an error: Expression 'redeem.redemption.Amount | number' is non-assignable
If I remove the filter, it works. I tried applying the same filter to the angular input demos and it works fine (https://docs.angularjs.org/api/ng/filter/number). Only difference I can see is I am binding to a an object on the scope and not a value directly. Is there something easy I am missing here?
I guess that what you are trying to do is to display the "formated value" of what they enter?
Then just remove the filter from the ng-model and in your controller watch the redeem.redemption.Amount and format it when the watch gets triggered. you will also need to set a timeout in order to allow the user to type, otherwise every time that the user hits a number the watch will try to format the number and the user won't be able to type anything.
The code that you have posted will never work because ng-model establishes a 2 way data binding with the property of the scope that you indicate, that's why you can not set filters there, it will only accept a property of the scope, that will be updated and from where it will read the value when it changes. The filter is a function with one input and retrieves a different output, think about it, if you set the filter, then Angularjs won't know where it has to set the changes of of the input.
Something like this:
app.controller('MyCtrl', function($scope,$filter,$timeout) {
$scope.testValue = "0.00";
var myTimeout;
$scope.$watch('testValue', function (newVal, oldVal) {
if (myTimeout) $timeout.cancel(myTimeout);
myTimeout = $timeout(function() {
if($filter('number')(oldVal, 2)!=newVal)
$scope.testValue = $filter('number')($scope.testValue, 2);
}, 500);
});
});
http://plnkr.co/edit/WHhWKdynw0nA4rYoy6ma?p=preview
Try tweaking the delay for the timeout, right now its been set to 500ms.
you cant put filter in ng-model directive.you can do it controller using this:
redeem.redemption.Amount=redeem.redemption.Amount.toFixed(2);
or you can use jquery to prevent keypress two digits after a decimal number like this:
$('.decimal').keypress(function (e) {
var character = String.fromCharCode(e.keyCode)
var newValue = this.value + character;
if (isNaN(newValue) || parseFloat(newValue) * 100 % 1 > 0) {
e.preventDefault();
return false;
}
});
<input type="number" id="decimal" class="text-center" ng-model="redeem.redemption.Amount | number:">