$setValidity inside validRegex directive - javascript

I have directive like this:
.directive('validRegex', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
ngModel.$parsers.unshift(function(viewValue) {
console.log(viewValue);
try {
var regex = new RegExp(viewValue);
ngModel.$setValidity('notRegex', true);
return viewValue;
} catch(e) {
ngModel.$setValidity('notRegex', false);
return undefined;
}
});
}
};
})
and I use it like:
<div class="col-sm-7">
<input class="form-control" valid-regex id="search-text" type="text" ng-model="selectedSearchText"/>
<span ng-show="selectedSearchText.$error.notRegex" class="form-error">
Invalid Regular Expression
<span class="icon-attention app_icon"></span>
</span>
</div>
<p>{{selectedSearchText}}</p>
If regex is invalid the the text don't show up as expected but no error message. I've search SO but didn't find a fix.

You have to enclose the input field with in a form as follows
<form name="form">
<div class="col-sm-7">
<input class="form-control" valid-regex id="search-text" type="text" ng-model="selectedSearchText" name="selectedSearchText"/>
<span ng-show="form.selectedSearchText.$error" class="form-error">
Invalid Regular Expression
<span class="icon-attention app_icon"></span>
</span>
</div>
<p>{{selectedSearchText}}</p>
</form>

Related

Binding input number with text in AngularJS

I need to bind inputs of type 'number' with a different models which are strings. I've managed to bind them using a directive like:
app.directive('input', function () {
return {
restrict: 'E',
require: 'ngModel',
priority:999999,
link: function (scope, elem, attrs, ctrl) {
//Check del tipo input
if (attrs.type.toLowerCase() !== 'number')
{
return;
}
//Paso a numero el valor a colocar
ctrl.$formatters.push(function (value)
{
return value ? parseFloat(value) : null;
});
}
};
});
And the HTML is like this:
<input class="form-control" type="number" ng-model="scopeValue" />
Up to here, there is no problem with binding. But, when I write a ng-repeat and ng-switch combined this directive is not executed. Sample code:
<div ng-repeat="attribute in attributes" ng-switch on="attribute.type">
<div class="input-group">
<span class="input-group-addon" id="basic-addon2">{{attribute.label}}</span>
<input class="form-control" ng-switch-when="text" ng-model="attribute.value" type="text" name="{{attribute.label}}" value="{{attribute.value}}">
<input class="form-control" ng-switch-when="number" ng-model="attribute.value" type="number" name="{{attribute.label}}" value="{{attribute.value}}">
</div>
</div>
Here the directive link code is never thrown and the inputs with number are never completed. As far as I know, the directive checks all the inputs and has the ngModel dependence. Why is it never executed?

AngularJS comparing two input values doesn't work as expected

I am trying to compare two password values using AngularJS. I have the submit button disabled until all the fields are valid. However, it is not working like it is supposed to. As soon as I enter the email and the first password, the submit button becomes enabled. But if I type something else in the second password field, then the submit button becomes disabled again. How do I do the validation even when nothing is entered in the second password field?
Here, is my form.
<form ng-submit="submit()" name="register" class="form-signin" novalidate>
<h1 class="form-signin-heading text-muted">
Register
</h1>
<input name="email" ng-model="email" type="email" class="form-control" placeholder="Email address" required>
<p class="help-block" ng-show="register.email.$dirty && register.email.$invalid">Please enter a valid email</p>
<input name="password" ng-model="password" type="password"class="form-control" placeholder="Password" required>
<input name="password_confirm" ng-model="password_confirm" type="password" class="form-control" placeholder="Confirm Password" validate-equals='password'>
<p class="help-block" ng-show="register.password_confirm.$dirty && register.password_confirm.$invalid">The passwords do not match</p>
<button ng-disabled="register.$invalid" class="btn btn-lg btn-primary btn-block" type="submit">Submit</button>
And here is the Javascript file(validateEquals.js)
'use strict';
angular.module('jwtApp').directive('validateEquals', function () {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
function validateEqual(value) {
var valid = (value === scope.$eval(attrs.validateEquals));
ngModelCtrl.$setValidity('equal', valid);
return valid ? value : undefined;
}
ngModelCtrl.$parsers.push(validateEqual);
ngModelCtrl.$formatters.push(validateEqual);
scope.$watch(attrs.validateEquals, function() {
ngModelCtrl.$setViewValue(ngModelCtrl.$viewValue);
});
}
};
});
If I can make a suggestion - do this:
<button ng-disabled="register.$invalid || password != password_confirm" class="btn btn-lg btn-primary btn-block" type="submit">Submit</button>
And not use the validateEqual implementation in your directive. Here's a fiddle: http://jsfiddle.net/jochenvanwylick/U3pVM/13972/ with your code and the fix. I wouldn't make it into a directive, nor would I try to hook into the $parsers and $formatters for the element.
try this
.directive('validateEquals', [function () {
return {
require: 'ngModel',
link: function (scope, elem, attrs, ctrl) {
var firstPassword = '#' + attrs.validateEquals;
elem.add(firstPassword).on('keyup', function () {
scope.$apply(function () {
var v = elem.val()===$(firstPassword).val();
ctrl.$setValidity('inputmatch', v);
});
});
}
}
on html you can check like this
<input type="password" id="input1" name="input1" ng-model="input1" ng-required/>
<input type="password" id="input2" name="input2" ng-model="input2" ng-required validate-equals="input1"/>
hope will help this solution :)
EDIT
can show error message like this
<div ng-show="myForm.$error">
<span ng-show="myForm.input2.$error.inputmatch">
Passwords don't match.
</span>
</div>

TypeError: undefined is not a function Input Validation AngularJS

I'm doing some input validation using angular, but when the function is called each of the elements come back as undefined. I've included the important code below, please let me know if this is not enough. I appreciate any help that I can get.
JS
angular.module('app.directives', [])
.directive('mrnCheck', [function () {
return {
require: 'ngModel',
link: function (scope, elem, attrs, ctrl) {
//console.log(firstMRN.val());
var firstMRN = '#' + attrs.mrnCheck;
elem.add('test');
//console.log(firstMRN.val());
//console.log(firstMRN);
elem.add(firstMRN).on('keyup', function () {
scope.$apply(function () {
ctrl.$setValidity('mrnmatch', elem.val() === $(firstMRN).val());
});
});
}
}
}]);
HTML
<div class = "row" ng-show="<?php echo $_SESSION["associate"]; ?>">
</br>
<form name = "UploadForm" class="input-group" role="form">
<div class="input-group">
<span class="input-group-addon">MRN</span>
<input type="MRN" ng-model="MRN1" class="form-control" id="MRN1" placeholder="Patient MRN" ng-required="" />
</div>
</br>
<div class="input-group">
<span class="input-group-addon">MRN</span>
<input type="MRN" ng-model="MRN2" class="form-control" id="MRN2" placeholder="Confirm MRN" ng-required="" mrn-Check="MRN1" />
<span ng-show="UploadForm.MRN2.$error.MRNmatch">MRN values must match!</span>
</div>
</form>
</div>
Error
at link (httpsomeLink/imageinbox/IIExpress/app/app.js:237:9)
at nodeLinkFn (httpsomeLink/imageinbox/IIExpress/app/assets/angular/angular.js:6704:13)
at compositeLinkFn (httpsomeLink/imageinbox/IIExpress/app/assets/angular/angular.js:6098:13)
at compositeLinkFn (httpsomeLink/imageinbox/IIExpress/app/assets/angular/angular.js:6101:13)
at nodeLinkFn (httpsomeLink/imageinbox/IIExpress/app/assets/angular/angular.js:6698:24)
at compositeLinkFn (httpsomeLink/imageinbox/IIExpress/app/assets/angular/angular.js:6098:13)
at nodeLinkFn (httpsomeLink/imageinbox/IIExpress/app/assets/angular/angular.js:6698:24)
at compositeLinkFn (httpsomeLink/imageinbox/IIExpress/app/assets/angular/angular.js:6098:13)
at compositeLinkFn (httpsomeLink/imageinbox/IIExpress/app/assets/angular/angular.js:6101:13)
at nodeLinkFn (httpsomeLink/imageinbox/IIExpress/app/assets/angular/angular.js:6698:24)
Please note, line 237 is the line that begins with elem.add. Also, somelink represents a real link, as I could not post the real one.
Please try this code. The input type="MRN" => type="text"
<form name="UploadForm" class="input-group" role="form">
<div class="input-group">
<span class="input-group-addon">MRN</span>
<input type="text" ng-model="MRN1" class="form-control" id="MRN1" placeholder="Patient MRN" ng-required="" />
</div>
<div class="input-group">
<span class="input-group-addon">MRN</span>
<input type="text" ng-model="MRN2" class="form-control" id="MRN2" placeholder="Confirm MRN" ng-required="" mrn-check="MRN1" />
<span ng-show="UploadForm.MRN2.$error.MRNmatch">MRN values must match!</span>
</div>
</form>
angular.module('app.directives', [])
.directive('mrnCheck', [function () {
return {
require: 'ngModel',
link: function (scope, elem, attrs, ctrl) {
//console.log(firstMRN.val());
var firstMRN = '#' + attrs.mrnCheck;
elem.add('test');
//console.log(firstMRN.val());
//console.log(firstMRN);
elem.add(firstMRN).on('keyup', function () {
scope.$apply(function () {
ctrl.$setValidity('mrnmatch', elem.val() === jQuery(firstMRN).val());
});
});
}
};
}]);

How data is passed from custom directive view to controller?

code for the directive template
//"textBox.html"
<div class="well">
<label class="control-label">Text</label>
<div class="controls">
<input id="label" type="text" class="txt span3" ng-model="label" placeholder='Label for text field...'>
<input type="text" class="span3" ng-model="value" placeholder='Default value...'>
<input type="text" class="span3" ng-model="helpText" placeholder="Help text...">
<input type="checkbox" class="span1" ng-model="required" ng-true-value="true" ng-false-value="false">Required
<input type="checkbox" class="span1" ng-model="advanced" ng-true-value="true" ng-false-value="false">Advanced?
<img src="../../images/bullet_cross.png" alt="Remove" style="cursor: pointer" id="text" border="0" ng-click="deleteField($event)">
</div>
</div>
directive is using like this in main html page
//"algorithm.html"
<text-box></text-box>
controller for the custom directive
//"controller.js"
var algorithm = angular.module('algorithmController',[]);
/***********directive to render text field***********/
algorithm.directive('textField' , function(){
return{
restrict: 'E',
templateUrl: '../partials/algorithm/textBox.html',
require: 'ngModel',
replace: true,
link: function(scope, iElement, iAttrs, ngModelCtrl) {
// how should i get updated data(i.e. if user change after typing) over here entered by user??
}
};
});
You can create an isolate scope using the '=' syntax, which will create two way binding to your controller and the directive. You don't even necessarily need ngModel required in your directive.
.directive("textField", function () {
return {
restrict : "E",
template : "<input type='text' ng-model='val'/>",
scope : {
val : "="
}
};
});
Here is a very simple example doing what you requested;
http://jsfiddle.net/smaye81/xaohrv53/2/

using datepicker on selecting date value not binding to model Angular js

i am using datepicker but here facing problem regarding model value not binding to model when i select date its nothing happen, any one can tell me where i am doing wrong must be appreciated. here i am sending my code.Showing date picker just problem after selecting date value not not binding to ng-model="user.dob".
signUpview.html
<div class="col-md-6">
<label for="datepicker" class="col-lg-5 form-label">Date Of Birth:</label>
<div class="col-lg-7">
<input type="text" class="form-control dateBirth" ng-model="user.dob" id="datepicker" name="datepicker" datepicker placeholder="Date Of Birth" required/>
<div class="error" ng-show="newUser_form.datepicker.$dirty && newUser_form.datepicker.$invalid">
<small class="error errorFields" ng-show="newUser_form.datepicker.$error.required"> Date is required.</small>
</div>
</div>
</div>
datepickerDirective.js
app.directive('datepicker', function() {
var linker = function(scope, element, attrs) {
element.datepicker().on('changeDate', function(){
console.log(scope);
$(".datepicker").hide();
});
}
return {
require: 'ngModel',
restrict: 'A',
link: linker
}
});
you can use ngModel.$setViewValue update the model property
app.directive('datepicker', function() {
var linker = function(scope, element, attrs,ngModelCtrl) {
element.datepicker().on('changeDate', function(){
console.log(scope);
ngModelCtrl.$setViewValue(value);//value is datepicker selected date;
$(".datepicker").hide();
});
}
return {
require: 'ngModel',
restrict: 'A',
link: linker
}
});

Categories