AngularJS Custom input control not performing validation - angularjs

I created a custom input control and trying to perform certain validation on blur.
But its not performing as expected. I want to use template like below instead of using jquery specific element.bind('blur')
template: '<input type="text" ng-blur="performvalidation()">',
Complete fiddle here
Please guide or correct what am I doing wrong. Thanks.

If you want to create custom validators you should add them to the ngModelController's $validators field. e.g.
angular.module('app').directive('strongSecret', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
ctrl.$validators.uppercaseValidator = function(value) {
return /[A-Z]/.test(value);
}
ctrl.$validators.numberValidator = function(value) {
return /[0-9]/.test(value);
}
ctrl.$validators.sixCharactersValidator = function(value) {
return value.length === 6;
}
}
};
});
Also instead of giving your directive a template you should just use it on an input element
<input ng-model="strongSecret" strong-secret name="strongSecret"/>
if you don't want to show the errors until the user clicks away from the input field you could do this
<ul ng-if="sampleForm.strongSecret.$touched" class="error-msgs" ng-messages="sampleForm.strongSecret.$error">
...
</ul>
Working jsFiddle: https://jsfiddle.net/e81kee9z/2/

Related

Value in ngModel not updated in Angular input view

I need to format the input values so I create a directive that use a template with require: 'ngModel' because I have to use ngModelController functions ($parsers, $formatters, etc.).
This is my HTML:
<div ng-model="myInputValue" amount-input-currency=""></div>
{{myInputValue}}
This is my directive:
.directive('amountInputCurrency', [function(){
return {
templateUrl: '../amountInputCurrency.tmpl.html',
require: 'ngModel',
restrict: 'A',
link: function(scope, elem, attrs, model) {
// ...
}
}
}
And this is my template:
<input type="text" ng-model="myInputValue">
The problem is that I can't updated the view after formatting the inserted value. For example if I write '1' I want change the value in this way:
model.$formatters.push(function(value) {
return value + '00';
}
Alternative I try to set an event in this other way:
<input type="text" ng-model="myInputValue" ng-blur="onBlur()">
scope.onBlur = function() {
model.$viewValue = model.$viewValue + '00';
// or model.$setViewValue(model.$viewValue + '00';);
model.$render();
};
The model.$viewValue changes, myInputValue (in the HTML with {{myInputValue}}) changes but not the value showed in the input box... which is the problem? Thanks!
----------------UPDATE----------------
Probably the problem is because I have 2 ng-model (one in the HTML and one in the template): https://github.com/angular/angular.js/issues/9296
How can I do? Both model refer to the same model...
Formatters change how model values will appear in the view.
Parsers change how view values will be saved in the model.
//format text going to user (model to view)
ngModel.$formatters.push(function(value) {
return value.toUpperCase();
});
//format text from the user (view to model)
ngModel.$parsers.push(function(value) {
return value.toLowerCase();
});
Try using $parsers to change the view to your desired value.
I hope this will help you.
Update:
angular.module('components', []).directive('formatParse', function() {
return {
restrict: 'E',
require: 'ngModel',
scope: { model: "=ngModel" },
template: '<input type="text" data-ng-model="model"></input><button type="button" data-ng-click="clickedView()">SetView</button><button type"button" data-ng-click="clickedModel()">SetModel</button>',
link: function ($scope, el, attrs, ngModelCtrl) {
format = "MMM Do, YYYY H:mm";
console.log($scope.model);
console.log(ngModelCtrl);
$scope.clickedView = function () {
ngModelCtrl.$setViewValue(ngModelCtrl.$viewValue);
};
$scope.clickedModel = function () {
$scope.model = 12; // Put here whatever you want
};
ngModelCtrl.$parsers.push(function (date) {
console.log("Parsing", date)
return date; // Put here the value you want to be in $scope.model
});
ngModelCtrl.$formatters.push(function (date) {
console.log("Formatting", date);
console.log($scope.model);
console.log(ngModelCtrl);
return +date * 2; // Put here what you want to be displayed when clicking setView (This will be in ngModelCtrl.$viewValue)
});
}
}
});
angular.module('someapp', ['components']);
Try using this code and tell if this helped to get the result you wanted.
If it does I suggest, to console.log the ngModelCtrl that you way you will understand more about the inner flow of angular.
In addition, just so you have some more information,
When you edit the input in the view the formatters function are fired to change the model accordingly.
If the value that has been entered is not valid you can return in your formatters function the ngModelCtrl.$viewValue to keep $scope.model with his old and true information.
When you change your scope variable (in your case $scope.model) the parsers functions will be fired to change the view value. (You don't need to use $render, you just need to decide when you want to change your $scope.model),
I suggest instead of using $setViewValue put the value you want in your scope variable and the parsers will act accordingly.

angular-wysiwyg form validation

I'm trying to use angular-wysiwyg and form validation. Instead of using the standard form.textArea.$dirty I've been updating a flag on the scope:
$scope.onTextChange = function (value) {
$scope.textContent = value;
$scope.isContentDirty = true;
...
}
Then I can use the property on my button:
<button ng-diabled="isContentDirty"></button>
But I'd prefer to do something like this:
<wysiwyg name="myTextArea" ng-model="textContent"></wysiwyg>
<button ng-disabled="!form.myTextArea.$dirty></button>
How could I make this work?
Here's an open issue sort of related:
https://github.com/TerryMooreII/angular-wysiwyg/issues/43
Here are the docs for this directive: https://github.com/TerryMooreII/angular-wysiwyg#usage
I found a solution that made me happy enough. It turns out that you can check the validity of any form item by reference, ie:
myForm.editor.$error
which would reference errors on the "editor" form item here:
<form name="myForm">
<wysiwyg name="editor"></wysiwyg>
</form>
When you go to the link step in the directive, you can set $parsers, which essentially allow you to invalidate your form if some conditions are met:
angular.module('foo').directive('wysiwyg', function() {
return {
restrict: 'E',
require: 'ngModel', //the 'value' of the form item
template: 'my template',
link: function(scope, elem, attrs, ngModel) {
function checkCustomError(viewValue) {
valid = viewValue.someCondition === 'someValue';
ngModel.$setValidity('customError', valid);
return viewValue;
}
ngModel.$parsers.unshift(checkCustomError);
}
}
}
And the error would show up under formName.directiveName.$error.customError
There are other ways to invalidate the ngModel as well, such as putting ng-maxlength on the directive, but I thought this was the most informative way of explaining.

In AngularJS, how to force the re-validation of a field in a form when another value in the same form is changed?

I have a form with few fields, however a select and an input field are coupled: the validation on the input depends on which value the user chooses in the select field.
I'll try to clarify with an example. Let's say that the select contains names of planets:
<select id="planet" class="form-control" name="planet" ng-model="planet" ng-options="c.val as c.label for c in planets"></select>
in the input I apply custom validation via a custom directive named "input-validation":
<input id="city" input-validation iv-allow-if="planet==='earth'" class="form-control" name="city" ng-model="city" required>
where this is the directive:
.directive('inputValidation', [function() {
return {
require: 'ngModel',
restrict: 'A',
scope: {
ivAllowIf: '='
},
link: function(scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function(viewValue) {
//input is allowed if the attribute is not present or the expression evaluates to true
var inputAllowed = attrs.ivAllowIf === undefined || scope.$parent.$eval(attrs.ivAllowIf);
if (inputAllowed) {
ctrl.$setValidity('iv', true);
return viewValue;
} else {
ctrl.$setValidity('iv', false);
return undefined;
}
});
}
};
}])
The full example can be examined in Plnkr: http://plnkr.co/edit/t2xMPy1ehVFA5KNEDfrf?p=preview
Whenever the select is modified, I need the input to be verified again. This is not happening in my code. What am I doing wrong?
I have done the same thing for validation of start-date on change of end-date. In the directive of start-date add watch for change of end-date and then call ngModel.$validate() in case end-date new value is defined.
scope.$watch(function () {
return $parse(attrs.endDate)(scope);
}, function () {
ngModel.$validate();
});
The important part to take is call to ngModel.$validate() inside the directive.
Note
you should use $validators for custom validations above to work. read here, $parsers is the old way - from angularjs 1.3 use $validators
FIXED PLUNKER LINK

Angular validation of dependent text field in an ngRepeat tag

I have the following ngRepeat code:
<div ng-repeat="drug in drugs | orderBy:'drugName'">
<input id="{{drug.drugName}}"
class="drugCheckbox"
name="{{drug.drugName}}"
type="checkbox" value="{{drug.drugName}}"
ng-model="foobar"
validate-foo
/>
{{drug.drugName}}
<!-- this is the error message, one per each repeat element -->
<span style="color:red" ng-show="myForm.{{drug.drugName}}.$error.summary">
Fill in the summary
</span>
<input type="text"
name="summary-{{drug.drugName}}"
id="summary-{{drug.drugName}}"
placeholder="Summary"/>
</div>
My validateFoo directive:
app.directive('validateFoo', function(){
return{
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attr, ctrl) {
ctrl.$parsers.unshift(function (viewValue) {
var id= attr.id;
//if the checkbox is checked, see if the text field has been filled in
if(viewValue) {
var val= document.getElementById('summary-' + id).value;
if(val.length == 0) {
ctrl.$setValidity("summary", false);
return undefined;
}
else {
ctrl.$setValidity(id, true);
return viewValue;
}
}
});
}
}
});
I cannot get the validation to work for any of the checkboxes, I am not clear on what to use for "ng-show" in the error message span element.
First of all that's because all fields will be registered in your formController under name {{drug.drugName}}.
Second thing is that there is no myForm.{{drug.drugName}}.$invalid in scope. You probably tried to do myForm[drug.drugName].$invalid. But it will not work anyway - look at 1.
I think that there still is no proper way to set name field dynamically in ng-repeat. Instead you need to create tour own directive, that will build repeated list elements as String, then append it to your HTML and $compile it place.
EDIT
I have developed one solution:
http://jsfiddle.net/ulfryk/gejfeLp7/
EDIT 2:
I've developed even simpler solution ( http://jsfiddle.net/ulfryk/5wq7539r/ ):
app.directive('fixRepeatedModelName', function () {
return {
link: function (scope, element, attrs, ngModelCtrl) {
if (!attrs.name) return;
ngModelCtrl.$name = attrs.name;
},
priority: '-100',
require: 'ngModel'
};
});
And add fix-repeated-model-name attribute to any ng-model with dynamic ({{ }} dependent) name placed inside ng-repeat. And it now works :)

How to disable angulars type=email validation?

How would you go about disabling, or at the very least changing, how Angular validates type=email inputs?
Currently, if you use type=email, Angular essentially double validates.. as the Browser (Chrome in this case) validates the email, and then angular does too. Not only that, but what is valid in Chrome foo#bar is not valid in Angularjs.
The best i could find, is ng-pattern, but ng-pattern simply adds a 3rd pattern validation for the input type.. instead of replacing Angular's email validation. heh
Any ideas?
Note: This is example is for angular 1.2.0-rc.3. Things might behave differently on other versions
Like others have stated it is a bit complex to turn off angulars default input validation. You need to add your own directive to the input element and handle things in there. Sergey's answer is correct, however it presents some problems if you need several validators on the element and don't want the built in validator to fire.
Here is an example validating an email field with a required validator added. I have added comments to the code to explain what is going on.
Input element
<input type="email" required>
Directive
angular.module('myValidations', [])
.directive('input', function () {
var self = {
// we use ?ngModel since not all input elements
// specify a model, e.g. type="submit"
require: '?ngModel'
// we need to set the priority higher than the base 0, otherwise the
// built in directive will still be applied
, priority: 1
// restrict this directive to elements
, restrict: 'E'
, link: function (scope, element, attrs, controller) {
// as stated above, a controller may not be present
if (controller) {
// in this case we only want to override the email validation
if (attrs.type === 'email') {
// clear this elements $parsers and $formatters
// NOTE: this will disable *ALL* previously set parsers
// and validators for this element. Beware!
controller.$parsers = [];
controller.$formatters = [];
// this function handles the actual validation
// see angular docs on how to write custom validators
// http://docs.angularjs.org/guide/forms
//
// in this example we are not going to actually validate an email
// properly since the regex can be damn long, so apply your own rules
var validateEmail = function (value) {
console.log("Validating as email", value);
if (controller.$isEmpty(value) || /#/.test(value)) {
controller.$setValidity('email', true);
return value;
} else {
controller.$setValidity('email', false);
return undefined;
}
};
// add the validator to the $parsers and $formatters
controller.$parsers.push(validateEmail);
controller.$formatters.push(validateEmail);
}
}
}
};
return self;
})
// define our required directive. It is a pretty standard
// validation directive with the exception of it's priority.
// a similar approach must be take with all validation directives
// you would want to use alongside our `input` directive
.directive('required', function () {
var self = {
// required should always be applied to a model element
require: 'ngModel'
, restrict: 'A'
// The priority needs to be higher than the `input` directive
// above, or it will be removed when that directive is run
, priority: 2
, link: function (scope, element, attrs, controller) {
var validateRequired = function (value) {
if (value) {
// it is valid
controller.$setValidity('required', true);
return value;
} else {
// it is invalid, return undefined (no model update)
controller.$setValidity('required', false);
return undefined;
}
};
controller.$parsers.push(validateRequired);
}
};
return self;
})
;
There you have it. You now have control over type="email" input validations. Please use a proper regex to test the email though.
One thing to note is that in this example validateEmail is run before validateRequired. If you need validateRequired to run before any other validations, then just prepend it to the $parsers array (using unshift instead of push).
Very simple. I had to alter the email regex to match a business requirement, so I made this directive that makes the email regex customizable. It essentially overwrites the original validator with my custom one. You don't have to mess with all the $parsers and $formatters (unless I'm missing something). So my directive was this...
module.directive('emailPattern', function(){
return {
require : 'ngModel',
link : function(scope, element, attrs, ngModel) {
var EMAIL_REGEX = new RegExp(attrs.emailPattern, "i");
ngModel.$validators["email"] = function (modelValue, viewValue) {
var value = modelValue || viewValue;
return ngModel.$isEmpty(value) || EMAIL_REGEX.test(value);
};
}
}
});
Then use it like this, supplying whatever email pattern you personally want:
<input type="email" email-pattern=".+#.+\..+"/>
But if you just want to permanently disable it then you could do this.
module.directive('removeNgEmailValidation', function(){
return {
require : 'ngModel',
link : function(scope, element, attrs, ngModel) {
ngModel.$validators["email"] = function () {
return true;
};
}
}
});
Then use it like this...
<input type="email" remove-ng-email-validation>
On HTML5 you can use the form's attribute novalidate to disable browser's validation:
<form novalidate>
<input type="email"/>
</form>
If you want to create a custom validator in angularjs, you have a good tutorial and example here: http://www.benlesh.com/2012/12/angular-js-custom-validation-via.html
Echoing nfiniteloop, you don't need to mess with the $parsers or $formatters to override the default validators. As referenced in the Angular 1.3 docs, the $validators object is accessible on the ngModelController. With custom directives you can write as many different email validation functions as you need and call them wherever you want.
Here's one with a very nice standard email format regex from tuts: 8 Regular Expressions You Should Now (probably identical to Angular's default, idk).
var app = angular.module('myApp', []);
app.directive('customEmailValidate', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
var EMAIL_REGEXP = /^([a-z0-9_\.-]+)#([\da-z\.-]+)\.([a-z\.]{2,6})$/;
ctrl.$validators.email = function(modelValue, viewValue) {
if (ctrl.$isEmpty(modelValue)) {
// consider empty models to be valid
return true;
}
if (EMAIL_REGEXP.test(viewValue)) {
// it is valid
return true;
}
// it is invalid
return false;
};
}
};
});
Here's one that removes validation entirely:
var app = angular.module('myApp', []);
app.directive('noValidation', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$validators.email = function(modelValue, viewValue) {
// everything is valid
return true;
};
}
};
});
To use in your markup:
<!-- 'test#example.com' is valid, '#efe#eh.c' is invalid -->
<input type="email" custom-email-validate>
<!-- both 'test#example.com' and '#efe#eh.c' are valid -->
<input type="email" no-validation>
In my project I do something like this (custom directive the erases all other validations including ones installed by angularjs):
angular.module('my-project').directive('validEmail', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl){
var validator = function(value){
if (value == '' || typeof value == 'undefined') {
ctrl.$setValidity('validEmail', true);
} else {
ctrl.$setValidity('validEmail', /your-regexp-here/.test(value));
}
return value;
};
// replace all other validators!
ctrl.$parsers = [validator];
ctrl.$formatters = [validator];
}
}
});
How to use it (note novalidate, it's required to turn off browser validation):
<form novalidate>
<input type="email" model="email" class="form-control" valid-email>

Resources