How to invalidate a form when using directive in AngularJS - javascript

i am working on a SPA and a form inside this app uses an input masked text box implemented using a third party library from here
i created a directive to set a mask for an IP address
angular
.module('app').directive('ipMask', [
function () {
return {
restrict: 'A',
require: '?ngModel',
link: function (scope, element, attrs, ngModel) {
element.mask('0ZZ.0ZZ.0ZZ.0ZZ', {translation: {'Z': {pattern: /[0-9]/, optional: true}}});
element.mask('099.099.099.099');
scope.$watch(attrs.ngModel, function (newValue, oldValue) {
//????????
});
}
};
}
]);
where my form code looks like
<div ng-controller="nodesListCtrl as vm">
<form role="form" name="frmNode">
<div class="form-group">
<label>Node IP :</label>
<input type="text" data-ip-mask ng-model="vm.myIp" name="CtrIp" class="input-sm form-control" placeholder="..." >
</div>
</form>
</div>
i want to invalidate the form if the IP address is wrong. i.e. i am expecting .ng-invalid class both on the form and and the control as well until the time it remains invalid. any suggestions ?

You don't need to use $watch. Just add a parser and/or formatter. Parsers are called when the view changes and formatters when the model changes. (This link can tell you more about those, as well as the other things available on ngModelController: https://docs.angularjs.org/api/ng/type/ngModel.NgModelController). Here's an example:
link: function (scope, element, attrs, ngModel) {
element.mask('0ZZ.0ZZ.0ZZ.0ZZ', {translation: {'Z': {pattern: /[0-9]/, optional: true}}});
element.mask('099.099.099.099');
ngModel.$parsers.unshift(function(value) {
var valid = isValid(value); // made up - use whatever validation technique based on that library
ngModel.$setValidity('ip', valid);
return valid;
});
ngModel.$formatters.unshift(function(value) {
var valid = isValid(value);
ngModel.$setValidity('ip', valid);
return valid ? value : undefined;
});
}

Related

AngularJS Custom Form Validation

I'm trying to make a field on a form valid by using the $valid class. I have the below HTML and JS code but even though the JS seems to work by modifying code editors, it doesn't validate the HTML. It doesn't seem to make it so $valid does anything but become true if the field has any text in it.
<input name="user" ng-model="user" ng-controller="SearchController" placeholder="User ID" required><br>
<span style="color:red" ng-show="searchForm.user.$dirty && searchForm.user.$invalid">A valid user ID is required.</span>
and
var searchApp = angular.module('searchApp', []);
searchApp.controller('SearchController', ['$scope', function ($scope) {
var users = ['11', '22', '33', '44']
return {
require: 'ngModel',
link: function (scope, element, attr, mCtrl) {
function idValidation(value) {
if (users.includes(value)) {
mCtrl.$setValidity('charE', true);
} else {
mCtrl.$setValidity('charE', false);
}
return value;
}
mCtrl.$parsers.push(idValidation);
}
};
}]);
The JS logic seems to work, but the HTML is not working correctly.
So you have a few minor errors in your code's logic to make this function correctly.
What you are attempting to do is create a custom validator. Your directive is using a $parser function, which is intended to parse a model's value for display. What you really want to be doing is working with a $validators function.
So, you would want to do something along the following:
var searchApp = angular.module('searchApp', []);
searchApp.directive('validUser', ['$scope', function ($scope) {
var users = ['11', '22', '33', '44']
return {
require: 'ngModel',
link: function (scope, element, attr, mCtrl) {
mCtrl.$validators.charE = function (value) {
return users.includes(value)
}
}
};
}]);
What happens is anytime the ngModel changes, it will run the value through the validators and determine if they are valid or invalid and automatically set ng-invalid-{name} or ng-valid-{name} (in this example, ng-invalid-charE and ng-valid-charE).
You can than use ngMessages to define your errors and they will show and hide as appropriate based on the validity.
Your ngController should more likely be a directive that adds the validator and your controller to contain the entire Search functionality/form HTML and be above your input to define your scope. Changing it to a directive would mean you'd remove ngController from the input and add an attribute for valid-user (as I've updated the name).

How do I add validation to ngModelCtrl from input field inside directive?

I have a custom directive and want to use the validators from an input field used inside this directive template. Is there a way to extend ngModelCtrl validators with the input validators?
This is my directive:
angular.module('myModule')
.directive('myUrl', function() {
return {
restrict: 'A',
require: ['ngModel', '^form'],
replace: true,
templateUrl: '/components/url/my-url.html',
scope: {},
link: function(scope, element, attrs, ctrls) {
var ngModelCtrl = ctrls[0];
var formCtrl = ctrls[1];
scope.formField = ngModelCtrl;
// Scope data vars
scope.url = '';
// Watchers
scope.$watch('url', function(newValue) {
ngModelCtrl.$setViewValue(newValue);
});
// Validators
var inputValidators = formCtrl['my-url'].$validators;
ngModelCtrl.$validators = angular.copy(inputValidators);
// Custom render
ngModelCtrl.$render = customRender;
function customRender() {
scope.url = ngModelCtrl.$viewValue;
}
}
}
});
This is my view:
<div>
<label>My URL</label>\
<input type="url" name="my-url" placeholder="http://" ng-model="url">
<div ng-messages="formField.$error" ng-show="formField.$invalid">
<span ng-message="url">Invalid URL.</span>
</div>
</div>
Here's a fiddle with this problem: https://jsfiddle.net/bsmaniotto/gzLmy1op/
Thanks.
EDIT:
Just realized that the problem is not on binding the input[url] validators to my custom directive ngModelCtrl's validators. The input[url] element is being validated and when an invalid input is entered the $modelValue is not set, and therefore, for my custom directive it is as nothing is inputted.
input validation is pretty easy in angular if you're using a controller. you can add:
ui-event: {keyup: 'controller.validationFunctionName(whatever)'}
Just fill in 'whatever' with the text in your input field and every time a key is let go it will check your validation function
If you want it to display an error beneath it just create another div that has an ng-if= to the result of that keyup function

Using angular form in directive template

I am using require: '^form' in my simple directive.
Then I trying to use this form in an ng-show but it doesn't seem to work.
Note: I don't want to pass the form name in as an attribute.
Can anyone see where i am going wrong? I only want the message to show when the form is invalid.
angular.module('xxx').directive('errorWall', errorWall);
function errorWall() {
return {
restrict: 'E',
require: '^form',
scope: {},
link: (scope, elm, attrs, frm) => {
scope.formCtrl = frm;
},
template: '<div ng-show="formCtrl.$invalid">You have error messages.</div>'
};
}
Make sure you've placed the directive inside the form with at least one input with a ng-model directive on it.
<form>
<input type="text" ng-model="name" required />
<error-wall></error-wall>
</form>
Here's a working fiddle https://jsfiddle.net/3gv8nvL3/3/ with one form required input.

Angular: directive access to form element

I have a form label containing an input:
<label data-live-email-check="http://www.example-service-uri.com/">
<span class="embedded-label">Email</span>
<input ng-model="formData.email"
type="email"
name="email"
placeholder="Email"
required/>
<span class="message" ng-show="emailValidationMessage">{{emailValidationMessage}}</span>
</label>
I want to create a directive that takes the URL provided by the data-live-email-check attribute and sends the email to that URL, validating whether or not it already exists.
angular.module("App").directive("liveEmailCheck", [function () {
return {
restrict: "A",
scope: {
ngModel: "="
},
link: function (scope, element, attrs) {
scope.$watch(
function(){
return scope.ngModel
},
function(newVal){
console.log(newVal);
}
);
}
}
}]);
I just want to watch the model on the input, and fire a request when it updates.
Since the directive is defined on the label element ngModel is not properly bound. What am I doing wrong? My watch expression is not logging anything because it never fires.
I know I could manually grab the input, but that just seems like I'd be breaking the "angular pattern" that I feel so "bound" by. The frustrating thing is that there seems to be so many ways to do everything in Angular that I can never tell if I'm approaching a problem correctly or not.
--Edit--
To provide the solution that I personally would take (out of ignorance of a "better" way), would be the following:
angular.module("App").directive("liveEmailCheck", [function () {
return {
restrict: "A",
require: ["^form"],
link: function (scope, element, attrs, ctrl) {
var formCtrl = ctrl[0];
scope.formEl = formCtrl[element.find("input").attr("name")];
scope.$watch(function(){return scope.formEl.$valid},
function(newVal){
console.log(newVal);
});
}
}
}]);
This WORKS, but I feel like it "breaks the angular rules".
A custom validation is written like this:
'use strict';
angular.module('App')
.directive('liveEmailCheck', function (){
return {
require: 'ngModel',
link: function (scope, elem, attr, ngModel){
ngModel.$validators.liveEmailCheck= function (value){
//Your logic here or in a factory
};
}
};
});
and then on your HTML it goes like
<input type="email" live-email-check="liveEmailCheck>
Basically you add your own validation to the set of build-in validations of angular.
What you need here is an ng-model asyncValidator. Here is a simple implementation of such a directive.
angular.module("App").directive('asyncEmailValidator', function ($http) {
return {
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
var emailValidationUrl = attrs.asyncEmailValidator;
ngModel.$asyncValidators.emailValidator = function (modelValue, viewValue) {
var value = modelValue || viewValue;
// NOTE: don't forget to correctly add the value to the url
return $http(emailValidationUrl + value).then(function (validationResponse) {
// NOTE: return rejected promise if validation failed else true
});
};
}
};
});
How you can use it in your case:
<label>
<span class="embedded-label">Email</span>
<input ng-model="formData.email"
async-email-validator="http://www.example-service-uri.com/"
type="email"
name="email"
placeholder="Email"
required/>
<span class="message" ng-show="<FormNameHere>.email.$error.emailValidator">
{{emailValidationMessage}}
</span>
</label>
This will be the right solution because it is implemented with angular ng-model validation which considers the validity of the model too.

Custom validation with AngularJS isn't triggered

I'm a beginner with AngularJS and for now I'm trying to create a registration form.
I tried to follow the instructions I found on the internet, but it looks like I cannot get my validation triggered. I'm not sure what is wrong.
Here's my JS for the validation:
var login = angular.module('login', []);
login.directive('repeatedValue', function () {
return {
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
ctrl.$validators.repeatedValue = function (modelValue, viewValue) {
alert("validation");
return false;
};
}
};
});
and the input field looks like this:
<input type="password" class="form-control" id="password2"
placeholder="Repeat password" value="" tabindex="3" ng-model="login.registerPassword2" repeatedValue/>
still, for some reason, even if I start typing into the field, the validation is not triggered and as a result I can still submit the form.
you must use right directive name in template (dash-delimited)
<input type="password" ... repeated-value/>
See Normalization chapter in docs https://docs.angularjs.org/guide/directive

Categories