custom directive is not validating form. why not? - javascript

What code changes need to be made to get the custom countparens directive below to provide the extra custom string validation shown below during form validation? The code below DOES successfully alert the user when the input field is empty, but it IS NOT alerting the user when the number of open parens ( and close parens ) is not equal.
I am using AngularJS. I used the documentation at this link (scroll to bottom) to design the code below.
Here is the html for the form:
<table>
<tr>
<td width=200>
<form name="userForm" ng-submit="rectangularForm(userForm.$valid)" novalidate>
<input type="text" name="fieldname" ng-model="nameofjsontype.fieldname" required />
<p ng-show="userForm.fieldname.$invalid && !userForm.fieldname.$pristine" class="help-block">Function is a required field.</p>
<span ng-show="userForm.nameofjsontype.fieldname.$error.countparens">The #( != #) !</span>
<br>
<button type="submit" ng-disabled="userForm.$invalid" >Click to submit</button>
</form>
</td>
</tr>
</table>
The javascript file containing the directive includes:
// create angular app
var myApp = angular.module('myApp', []);
// create angular controller
myApp.controller('myController', ['$scope', '$http', function($scope, $http) {
$scope.nameofjsontype = {type:"nameofjsontype", fieldname: 'some (value) here.'};
$scope.rectangularForm = function(isValid) {
// check to make sure the form is completely valid
if (isValid) {
var funcJSON = {type:"nameofjsontype", fieldname: $scope.nameofjsontype.fieldname};
$http.post('/server/side/controller', funcJSON).then(function(response) {
$scope.nameofjsontype = response.data;
});
}
};
}]);
myApp.directive('countparens', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$validators.countparens = function(modelValue, viewValue) {
if (ctrl.$isEmpty(modelValue)) {
// consider empty models to be valid
return true;
}
if (
($scope.nameofjsontype.fieldname.match(/\)/g).length) == ($scope.nameofjsontype.fieldname.match(/\(/g).length)
) {
// it is valid
return true;
}
// it is invalid
return false;
};
}
};
});

Your markup should be using userForm.fieldname.$error.countparens to show the error. The field bound to the userForm is NOT the same as your ngModel value. See plunker for what I mean
<span ng-show="userForm.fieldname.$error.countparens" class="help-block">The #( != #) !</span>
You are also not using your directive on your input element:
<input type="text" name="fieldname" ng-model="nameofjsontype.fieldname" required data-countparens=""/>
In your directive
you should be using modelValue and not the scope value when doing your matching AND
you need to cater for when there are no matches to ( or )
.
myApp.directive('countparens', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$validators.countparens = function(modelValue, viewValue) {
return ctrl.$isEmpty(modelValue) ||
((modelValue.match(/\)/g) || []).length == (modelValue.match(/\(/g) || []).length);
};
}
};
});

Related

Focus on empty ng-model data after ng-readonly=true

I have a form input. When the page is loaded the input has "ng-readonly=true" property and it only shows the data.
When I double click (ng-dblclick) the property "ng-readonly" changes to false and I can edit the input.
For all this, it is working currectly. But when the data
(ng-model="school.fax") a row data is empty it does do a focus, and I need to click on the input to focus and start writing.
It does not happen when the data is not empty (ng-model="school.fax" have value, get value from server API) and in this case, it's working correctly
The question:
How can I focus on the empty input and start writing without need to click the input row?
The code:
HTML
<label>
<input class="inputs"
type="text"
ng-readonly="!edit_school_fax"
ng-dblclick="editSchoolFax(true)"
ng-model="school.fax"/>
</label>
JS
$scope.editSchoolFax = function(edit) {
$scope.edit_school_fax = edit;
};
FYI
I try, and it does not work for me:
Add "autofocus" inside the input
<input autofocus
Use directive like this solution: LINK
add custom directive
link(scope, element, attrs) {
scope.$watch(attrs.someAttrs, (newVal, oldVal) => {
if (newVal === true && newVal !== oldVal) {
$timeout(() => {
element
.focus()
.select();
});
}
});
},
Use a custom directive that adds a focus method to the ngModelController:
app.directive("inputFormFocus", function() {
return {
require: "ngModel",
link: postLink
};
function postLink (scope, elem, attrs, ngModel) {
console.log("postLink");
console.log(ngModel);
ngModel.focus = function() {
elem[0].focus();
}
}
})
Usage
<form name="form1">
<input input-form-focus
name="fax"
class="inputs"
type="text"
ng-readonly="!edit_school_fax"
ng-dblclick="editSchoolFax(true)"
ng-model="school.fax"/>
</form>
$scope.form1.fax.focus();
The DEMO
angular.module("app",[])
.controller("ctrl",function($scope){
$scope.editSchoolFax = function(edit) {
$scope.edit_school_fax = edit;
};
$scope.school = { fax: "555-100-1234" };
$scope.faxFocus = function() {
$scope.edit_school_fax = true;
$scope.form1.fax.focus();
};
})
.directive("inputFormFocus", function() {
return {
require: "ngModel",
link: postLink
};
function postLink (scope, elem, attrs, ngModel) {
ngModel.focus = function() {
console.log(attrs.name + " focus");
elem[0].focus();
}
}
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="ctrl">
<form name="form1">
<input input-form-focus
name="fax"
class="inputs"
type="text"
ng-readonly="!edit_school_fax"
ng-dblclick="editSchoolFax(true)"
ng-model="school.fax"/>
</form>
<button ng-click="faxFocus()">Focus and Edit</button>
</body>

Number validation in range in AngularJS

I am creating a project using AngularJS and I want to integrate validation in AngularJS. My requirement is that the number should be between the 1-4096 in AngularJS.
Here is my code:
<div class="col-lg-6 col-md-6">
<input type="text" class="form-control" placeholder="VLAN ID" ng-model="exchange.vlanId" valid-number/>
</div>
You should create very simple directive that would allow to validate input in reusable, configurable and declarative way.
You already have valid-number attribute, so the implementation can look like:
angular.module('demo', []).directive('validNumber', [function() {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ctrl) {
if (!ctrl) return;
var range = attrs.validNumber.split(',').map(Number);
ctrl.$validators.validNumber = function(value) {
return value >= range[0] && value <= range[1];
};
}
};
}]);
.error {color: brown;}
<script src="https://code.angularjs.org/1.4.8/angular.min.js"></script>
<div ng-app="demo">
<form name="form">
<input type="text" class="form-control" placeholder="VLAN ID" name="vlanId"
ng-model="exchange.vlanId" valid-number="1,4096" />
</form>
<div class="error" ng-show="form.$dirty && form.vlanId.$error.validNumber">VLAN ID should be in range 1-4096.</div>
</div>
You can bind an event on the input and call a function with passing the model in it:
<input type="text" class="form-control" placeholder="VLAN ID"
ng-model="exchange.vlanId"
ng-keydown="obj.validate(exchange.vlanId)" valid-number/>
Now in the controller you can define a method:
yourApp.controller('theController', ['$scope', function($scope){
$scope.obj = {
validate:function(val){
if(val < 1 || val > 4096){
alert(val+' is out of range');
}
}
};
}]);
And the directive valid-number can also be used:
yourApp.directive('validNumber', function($scope){
return {
restrict:'E',
link:function(scope, el, attrs){
el.on('keydown', function(){
el.css('border', function(){
return scope.exchange.vlanId < 1 || scope.exchange.vlanId > 4096
? "red" : "green";
});
});
}
};
});

Add custom validation to AngularJS form

In below form I'm checking that an e-mail address is required :
http://jsfiddle.net/U3pVM/16994/
I want to extend the validation so that it check that the first two characters begin with 'DD' . It seems I need to add a custom directive but I'm unsure how to link the e-mail fields with the directive ?
fiddle code :
<form ng-app="myApp" ng-controller="validateCtrl"
name="myForm" novalidate>
<p>Email:<br>
<input type="email" name="email" ng-model="email" required>
<span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
<span ng-show="myForm.email.$error.required">Email is required.</span>
</span>
</p>
<p>
<input type="submit"
ng-disabled="myForm.user.$dirty && myForm.user.$invalid ||
myForm.email.$dirty && myForm.email.$invalid">
</p>
</form>
var app = angular.module('myApp', []);
app.controller('validateCtrl', function($scope) {
});
app.directive("myValidator", function(){
// requires an isloated model
return {
// restrict to an attribute type.
restrict: 'A',
// element must have ng-model attribute.
require: 'ngModel',
link: function(scope, ele, attrs, ctrl){
// add a parser that will process each time the value is
// parsed into the model when the user updates it.
ctrl.$parsers.unshift(function(value) {
if(value){
// test and set the validity after update.
var valid = value.charAt(0) == 'D' && value.charAt(1) == 'D';
ctrl.$setValidity('invalidAiportCode', valid);
}
return valid ? value : undefined;
});
}
}
});
Here's how I would do it, using an authentication example:
The simple markup:
<input type="email" ng-model="existingUser.email">
<button ng-click="login(existingUser)">Login</button>
The controller:
auth.controller('AuthCtrl', '$scope', 'validation', function($scope, validation) {
$scope.existingUser = {
email: '',
password: ''
}
$scope.login = function() {
validation.validateSignin($scope.existingUser)
.catch(function(err) {
// The validation didn't go through,
// display the error to the user
$scope.status.message = err;
})
.then(function(res) {
// Validation passed
if (res === true) {
// Do something
}
});
}
}
The factory:
auth.factory('validation', ['$q', function($q) {
return {
validateSignin: function(existingUser) {
var q = $q.defer();
if (existingUser.email.substring(0,2) !== 'DD') {
q.reject('The email must start with "DD"');
}
q.resolve(true);
return q.promise;
}
}
}]);
Let me explain what's happening, first I'm creating a factory which will carry out the validation. Then I'm creating a promise with a resolve and a reject method, the reject method will be called if the validation failed, and if it succeeded then the resolve will be called. Then in your controller you can do things based on the outcome.
Let me know if anything is unclear.

Directive to accept numbers greater than 0 and less than 100

I am trying to create an angular Directive which returns an error when the input of the textfield is less than 5 and greater than 200 i am trying with this code and for some reason it isnt working any help would be appreciated.
JS
app.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, '');
console.log("inputValue"+inputValue);
if(parseInt(inputValue) > 200 || parseInt(inputValue) < 5){
return '';
}
if (transformedInput!=inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});
HTML
<div ng-controller="MyCtrl">
<input type="text" ng-model="number" required="required" numbers-only="numbers-only" />
</div>
The plunker that i created is this (http://plnkr.co/edit/QKifStiFmHBF8GhcH3Ds?p=preview)
Any help would be appreciated!
I have given a directive that takes care of your model value to always contain int values between 5 and 200. A 'ng-invalid' class will be added when you do setValidity to false. Using that you can use css to display error to the user. In case you want your input to be updated with the correct model value in case of error, you can do it in the blur event.
app.directive('numbersOnly', function(){
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
if(parseInt(inputValue) <= 200 && parseInt(inputValue) >= 5){
modelCtrl.$setValidity('numbersOnly', true);
return inputValue;
} else {
modelCtrl.$setValidity('numbersOnly', false);
return modelCtrl.$modelValue;
}
});
}
};
});
angular already has perfect directives for that. all you need is a form and use Min Max inside input tag
<form name="ue.form">
<input type="number" ng-model="ue.num" name="num" min="5" max="200" >
</form>
<p ng-if="ue.form.$error">
number must be less than 200 and greater than 5
</p>
or you can handle each error separately:
<p ng-if="ue.form.num.$error.min">
number must be greater than 5
</p>
<p ng-if="ue.form.num.$error.max">
number must be less than 200
</p>
if number is not in range 5-200 then form validotor throw an error.
min and max work only with input type="number".
https://plnkr.co/edit/?p=preview
Here's what I would suggest:
Use ng-model-options="{ updateOn: 'blur' }" so that model gets updated only on blur.
Try this code in directive:
app.directive('numbersOnly', function(){
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, element, attrs, ngModel) {
element.on('blur', function() {
if (ngModel.$viewValue < 5 || ngModel.$viewValue > 200) {
ngModel.$setViewValue('');
element.val('');
}
});
}
};
});
You can use ng-messages for these kind of validation purposes
We always can customize ng-messages with our needs.
you can create two directives for min and max. In your case your minimum value is 5 and max is 200, we dont need to hardcode our values inside the directives.
You dont need to worry for adding error messages in your directive. ng-messages will do it for you. You just need to put your messages inside ng-messages div.
Directive
module.directive("min", function () {
return {
restrict: "A",
require: "ngModel",
link: function (scope, element, attributes, ngModel) {
ngModel.$validators.min = function (modelValue) {
if (!isNaN(modelValue) && modelValue !== "" && attributes.min !== "")
return parseFloat(modelValue) >= attributes.min;
else
return true;
}
}
};
});
module.directive("max", function () {
return {
restrict: "A",
require: "ngModel",
link: function (scope, element, attributes, ngModel) {
ngModel.$validators.max = function (modelValue) {
if (!isNaN(modelValue) && modelValue !== "" && attributes.max !== "")
return parseFloat(modelValue) <= attributes.max;
else
return true;
}
}
};
});
Usage
<form name="myform">
<input type="text" name="minmax" ng-model="number" required="required" min="5" max="200"/>
<div data-ng-messages="myform.minmax.$error" class="error-messages">
<div data-ng-message="min">YOu cant enter below 5</div>
<div data-ng-message="max">You cant enter above 200</div>
</div>
</form>
Here is my pluker example

Custom directive for telephone format using angularjs

I am trying to write custom directive for USA telephone number using angularjs and need to preserve the data type of the field as integer.Here is the jsfiddle directive and need help to complete the directive.
If user enters a valid telephone no (exactly 10 numbers ie.1234567890) then input should split into 3 chunks as 123-456-7890 when the user moves to next control.otherewise I should show error message "not a valid number".
<div ng-app="myApp" ng-controller="myCtrl">
<form name="myForm">
<input type="text" ng-model="telephone" phoneformat name="input1" />
<span class="error" ng-show="myForm.input1.$error.telephone">Numbers only!</span>
<span class="error" ng-show="myForm.input1.$error.telephone">Exact 10 Numbers only!</span>
</form>
</div>
var myApp = angular.module("myApp", []);
var myCtrl = myApp.controller("myCtrl",["$scope", function($scope) {
$scope.telephone = "1234567890";
}]);
myApp.directive("phoneformat", function () {
return {
restrict: "A",
require: "ngModel",
link: function (scope, element, attr, ngModelCtrl) {
var phoneformat = function () {
}
}
};
});
It looks like you want to leverage the $error property of the form to drive validation. To do this, you will need to call $setValidity in the ngModelCtrl that you have required into your directive:
var myApp = angular.module("myApp", []);
var myCtrl = myApp.controller("myCtrl",["$scope", function($scope) {
$scope.telephone = "1234567890";
}]);
myApp.directive("phoneformat", function () {
return {
restrict: "A",
require: "ngModel",
link: function (scope, element, attr, ngModelCtrl) {
//Parsing is performed from angular from view to model (e.g. update input box)
//Sounds like you just want the number without the hyphens, so take them out with replace
var phoneParse = function (value) {
var numbers = value && value.replace(/-/g, "");
if (/^\d{10}$/.test(numbers)) {
return numbers;
}
return undefined;
}
//Formatting is done from view to model (e.g. when you set $scope.telephone)
//Function to insert hyphens if 10 digits were entered.
var phoneFormat = function (value) {
var numbers = value && value.replace(/-/g,"");
var matches = numbers && numbers.match(/^(\d{3})(\d{3})(\d{4})$/);
if (matches) {
return matches[1] + "-" + matches[2] + "-" + matches[3];
}
return undefined;
}
//Add these functions to the formatter and parser pipelines
ngModelCtrl.$parsers.push(phoneParse);
ngModelCtrl.$formatters.push(phoneFormat);
//Since you want to update the error message on blur, call $setValidity on blur
element.bind("blur", function () {
var value = phoneFormat(element.val());
var isValid = !!value;
if (isValid) {
ngModelCtrl.$setViewValue(value);
ngModelCtrl.$render();
}
ngModelCtrl.$setValidity("telephone", isValid);
//call scope.$apply() since blur event happens "outside of angular"
scope.$apply();
});
}
};
});
Working fiddle. This was just a quick way of demonstrating the parser and formatter pipelines that are used in ngModel, along with $setValidity -- which is used to populate the $error field(s).
Update: To use this same phone validation across multiple phones, use form with $error. Notice that each input gets a unique name that is used with myForm (name of form). Both use $error.telephone:
<form name="myForm">
Mobile Phone:
<input type="text" ng-model="mobilephone" phoneformat name="mobilephone" />
<span class="error" ng-show="myForm.mobilephone.$error.telephone">
Exact 10 Numbers only!
</span>
<br />
Home Phone:
<input type="text" ng-model="homephone" phoneformat name="homephone" />
<span class="error" ng-show="myForm.homephone.$error.telephone">
Exact 10 Numbers only!
</span>
</form>
Updated fiddle.
You might want to use http://angular-ui.github.io/ui-utils/ Mask directive.
Working Fiddle: http://jsfiddle.net/HB7LU/6581/
myApp.directive("phoneFormat", function () {
return {
restrict: "A",
link: function (scope, element, attr) {
element.bind('change', function() {
if ( this.value.length === 10 ) {
var number = this.value;
this.value = number.substring(0,3) + '-' + number.substring(3,6) + '-' + number.substring(6,10)
}
else {
document.querySelector('.helpblock').innerHTML = 'error in formatting';
}
});
}
};
});
Iv'e extended your original fiddle. here's the result:
http://jsfiddle.net/10k58awt/
You can find splittedNumber array (contains 3 parts of number) on form submission
js:
var myApp = angular.module("myApp", []);
var myCtrl = myApp.controller("myCtrl", ["$scope", function ($scope) {
$scope.telephone = "1234567890";
$scope.submit = function () {
var splittedNumber = [$scope.telephone.substring(0, 3), $scope.telephone.substring(3, 6), $scope.telephone.substring(6, 10)];
// Do something with splitted number
console.log(splittedNumber);
};
}]);
myApp.directive("phoneformat", function () {
return {
restrict: "A",
require: "ngModel",
link: function (scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function (phoneInput) {
phoneInput = phoneInput.trim();
if (phoneInput && phoneInput.length == 10 && !isNaN(phoneInput)) {
ctrl.$setValidity('phoneformat', true);
return phoneInput;
} else {
ctrl.$setValidity('phoneformat', false);
return undefined;
}
});
}
};
});
html:
<div ng-app="myApp" ng-controller="myCtrl">
<form name="myForm" novalidate ng-submit="myForm.$valid && submit()">
<input type="text" ng-model="telephone" phoneformat name="input1" /> <span class="error" ng-show="myForm.input1.$error.phoneformat">Invalid US Phone number!</span>
<div>
<button class="btn btn-primary" type="submit" ng-class="{'disabled': !myForm.$valid}">submit</button>
</div>
</form>
</div>

Categories

Resources