Angular can I have 2 ng-pattern to validate the same filed - angularjs

My current input looks like this
<input type="email" name="email"
ng-pattern="emailRegex"
ng-change="emailChanged()"
required />
My ng-pattern="ctrl.emailRegex" validates if an email is valid or not
/^[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{1,63}$/;
But I would like to block info#, admin#, help#, sales# emails, so I changed the regex to
/^(?!(?:info|admin|help|sales)#)[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{1,63}$/
So far so good, but I would like to show
Invalid email
to "invalid#!!!!!.com!"
and
info#, admin#, help#, sales# emails are not allowed
to info#test.com
How can I have 2 ng-pattern in the same input?
Thanks

You can validate only one pattern for an input. And, even if you can sort of do it somehow by using a directive, it would be too dirty a solution. Instead, I would recommend validating the input against regex(es) inside the function of ng-change and use formName.inputName.$setValidity to set custom validity of the input. This lets you have a fallback if one pattern is passed.
So, for example, ctrl.emailChanged could probably have something like this,
ctrl.emailChanged = function() {
var emailPattern = /^[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{1,63}$/;
var customValidateEmail = /^(?!(?:info|admin|help|sales)#)[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{1,63}$/;
if(!emailPattern.test(ctrl.registrationForm.email)) {
// Invalid email
} else if (customValidateEmail.test(ctrl.registrationForm.email)) {
// handle accordingly
}
// rest of the things
...
}
Alternatively, you can move the validation logic to another function and just call it from emailChanged.

Related

Angular 5 disable and enable checkbox based on condition

I'm trying to implement a validation in which i want to disable the button if a specific value entered by user matches the value returned from a service, below is my code:
In the component, i call the service which returns the usernames like below, here is the console log for (UserNames):
0:{Name: "John", userId: "23432"}
1:{Name: "Smith", userId: "12323"}
2:{Name: "Alan", userId: "5223"}
3:{Name: "Jenny", userId: "124"}
in the template, i use NgFor to iterate over the usernames like below
<div *ngFor="let id of UserNames let i = index;">
<input type="radio" name="radio" [checked]="UserNames.userid" (click)="Submit(UserInput)"> <span>Submit</span>
</div>
What i want to achieve is if i enter 23432 the button should disabled because the service already returns userId with this value, unless a new user id entered the button should be enabled.
So the general case of disabling a submit button in the way you're describing would look like:
<button type="submit" [disabled]="someValidationFn()" ...>
and someValidationFn() would, according to the use case you described, contain something like
return UserNames.find(name => { return name.userId === userInput;}));
where userInput is a separate property in the component bound to some user-entered value, presumably via an open text input like
<input name="userInput" [(ngModel)]="userInput" type="text" placeholder="Enter some user id">
But, from the markup snippet you pasted*, I'm not clear that you have that "text" input separate from the radio button group. If the radio button group is meant to have submit actions attached to its individual buttons (it shouldn't), then you're actually guaranteed that the user selection will contain a userId which exists in your UserNames array: the only inputs you're offering are based on the data which came from your service in the first place.
Based on the use case you're describing, I'm not sure why you'd have the radio button group. It sounds like you would just want that text input field with a validation method to make sure that user input does not already exist in the UserNames.
Because I wrote a bunch of abstract snippets there, I thought it might be helpful to show some basic html and js where I put it all together:
// html
<form submit="someSubmitAction()">
<input name="userInput" [(ngModel)]="userInput" type="text" placeholder="Enter some user id">
<button type="submit" [disabled]="someValidationFn()">Submit</button>
</form>
// js
/* don't forget your #Component annotation and class declaration -- I'm assuming these exist and are correct. The class definition encloses all the following logic. */
public userInput: string;
public UserNames: any[];
/* then some service method which grabs the existing UserNames on component's construction or initialization and stores them in UserNames */
public someValidationFn() {
return UserNames.find(name => { return name.userId === userInput;}));
}
public someSubmitAction() {
/* presumably some other service method which POSTs the data */
}
*speaking of the snippet you pasted, there are a couple of errors there:
*ngFor="let id of UserNames <-- you won't get an id by referencing into the UserNames array here; you'll get a member of the UserNames array in each iteration -- i.e., you'd get {Name: "John", userId: "23432"}, then {Name: "Smith", userId: "12323"}, and so on. That's not necessarily an error, but I'm assuming that, b/c you used id as your variable name, you were expecting just the userId field. Otherwise you'd have to use {{id.userId}} in each iteration to access the actual id.
And bob.mazzo mentions another issue with the use of the [checked] attribute

issue with ngPattern

I am trying to design a nifty expiration date input on a credit card checkout form that will automatically insert a " / " between expiration month and year while the user is typing. The model no longer picks up the input value since I have introduced ngPattern validation to the input. Angular only allows a model to pick up the input value once the validation has succeeded. This basically makes my nifty feature not work due to my code. Can someone find a way around this. below is my code.
html
<input ng-keyup="checkout.updateExp()" class="form-control" type="text" maxlength="7" placeholder="mm / yy" required autocomplete="off" name="exp" ng-pattern="/\d{2}\s\/\s\d{2}/" ng-model="checkout.cf.exp">
controller function
vm.updateExp = function(){
var separator=" / ";
//add separator
if(vm.cf.exp.length==2){//-----> cannot process since ngPattern makes exp undefined till pattern is met
vm.cf.exp = vm.cf.exp.substring(0,2) + separator;
}
//remove separator
if(vm.cf.exp.length==4){
vm.cf.exp = vm.cf.exp.substring(0,1);;
}
};
Why not validate it manually using a regular expression instead of having it done using ng-pattern? You can set the $validity of the field manually just like angular would do it using ng-pattern.
In the html add
ng-keyup="checkout.updateExp(form.exp)" name="exp"
form.exp is the form and then the name of the input field. I do not know what the form name is so you will have to replace it accordingly.
vm.updateExp = function(formModel){
/* existing code omitted */
var expression = /\d{2}\s\/\s\d{2}/; // create RegEx
formModel.$setValidity("pattern", expression.test(vm.cf.exp)); // set validity to whatever name you want, I used the name pattern
};

Input is invalid even when it's error is empty

I'm trying to create my own validation for password confirm, and putting my error on $error. this is my code:
html:
<input ng-model="user.password2" type="password" name="password2" required
ng-keyup="confirmPassword(user.password, user.password2)">
<div ng-messages="register.password2.$error" ng-if="register.password2.$dirty">
<div ng-message="required">Password is required</div>
<div ng-message="passwordsDontMatch">Passwords don't match</div>
</div>
JS:
$scope.confirmPassword = function (pass1, pass2) {
if (angular.isUndefined(pass1) || angular.isUndefined(pass2) || pass1.trim() != pass2.trim()) {
$scope.register.password2.$error["passwordsDontMatch"] = true;
} else {
delete $scope.register.password2.$error["passwordsDontMatch"];
}
console.log($scope.register.password2.$error);
};
it looks like it's working. when the passwords are the same, the message is not displayed and indeed the $error object is empty. But the input is still invalid: ($scope.register.password2.$invalid == true)
you can see what I'm talking about in this plunkr: http://plnkr.co/edit/ETuVqsdSaEBWARvlt4RR?p=preview
try 2 identical passwords. the message will disappear but when you blur from the input, it's still red because internally it's $invalid
The problem probably comes from the fact that you're not typing a password in the first field that matches your regex pattern. The first password is thus undefined, since it doesn't respect the ng-pattern validation rule.
That said, you shouldn't modify the $error array directly. Instead, you should set the validity of the field using $setValidity(). That will not only set and remove the error automatically, but also deal with the $invalid/$valid properties, add and remove the CSS classes, etc.
var valid = !((angular.isUndefined(pass1) || angular.isUndefined(pass2) || pass1.trim() != pass2.trim()));
$scope.register.password2.$setValidity("passwordsDontMatch", valid);
Here's a working example. But remember to enter a valid password in the first place.
Also, instead of implementing this check with ng-keyup, you should make it a directive, which would add a validator to the validators of the form input. This would make sure the check is made whatever the way the second password is entered (i.e. via copy/paste using the mouse only, or simply by prepopulating the form programmatically.

Warnings in AngularJs

Angularjs has great infrastructure for form validation and showing error messages. But, I am in a situation that I have to show a warning message to a user in a specific scenario. Here is the diagram of my simple form
The form has required and pattern validation applied on both fields. In addition to this validation I want a warning message to be displayed to the user if VatAmount is not 20 percent of the InvoiceAmount. The warning will differ from validation in following aspects
It will not prevent the form submission
It will only appear if both fields (InvoiceAmount and VATAmount) are
valid
The warning should have a button or link that would read "Change and
proceed". When user presses that button the warning message will
hide and focus will be set to VATAmount field.
I believe this is a prefect use case for creating a directive. Actually, I have given it a try and put my effort in the form of a plunker. But my directive does not handle following cases
It appears even if the fields involved in warning are invalid
The show and hide functionality is not implemented (have no idea how
to target it)
Here is the link to the plunker
Your plunkr demo was on the right track; really you just needed to check for the special cases of when one of the values was empty.
I'd suggest calculating the fraction and storing it in the scope, and then watching that to see whether you should display your tax rate warning. Here's how to calculate the fraction. If either invoice.Amount or invoice.VAT is empty, the fraction will be set to null.
if (amt == null || vat == null) {
$scope.warning.fraction = null;
return;
}
$scope.warning.fraction = vat / amt;
This works because those properties will be set to undefined if the user doesn't enter a valid number due to your use of ng-pattern.
However, while it's nice to encapsulate this in a directive, you don't need to compile the template yourself. Just use the built-in ng-transclude directive. Then you can include a button that references the current scope like this:
<vat-warning>
Vat Amount is not 20%.
<button ng-click="invoice.VAT = invoice.Amount / 5">change</button>
</vat-warning>
Your directive would contain this declaration:
transclude: true,
template: '<span class="alert-warning" ng-show="warning.show" ng-transclude></span>'
Plus a controller to update the directive's local scope to manipulate the warning object. Here's an updated demo.
You need to calculate visibility of vat-warning tag in controller on basis of $error.required and $error.pattern of invoiceAmount and vatAmount and then use it as below:
$scope.isInvoiceAmountInvalid = function () {
var error = $scope.invoiceForm.invoiceAmount.$error;
var required = error.hasOwnProperty("required") && error.required;
var pattern = error.hasOwnProperty("pattern") && error.pattern;
console.log("Inside isInvoiceAmountInvalid", error, required, pattern);
return (required || pattern);
};
$scope.isVatAmountInvalid = function () {
var error = $scope.invoiceForm.vatAmount.$error;
var required = error.hasOwnProperty("required") && error.required;
var pattern = error.hasOwnProperty("pattern") && error.pattern;
console.log("Inside isVatAmountInvalid", error, required, pattern);
return (required || pattern);
};
Here is an updated plunker for the same

maxlength on field not working with Karma

I have a field with a maxlength of 6, but somehow the following way of entering data results in 7 chars being allowed:
<input type="text" name="myName" maxlength="6" ng-model="myModel">
this is the test bit:
input('myModel').enter('1111117');
expect(input('myModel').val()).toBe(111111);
and this is the result
expected 111111 but was "1111117"
I suppose this has to do with the model being used instead of the real field, but how would I test this then in Karma?
The problem is caused because maxlength only limits the input from the user, and not the actual value of the input. For example, if you try to use jQuery's val() on your input, it would accept any length of the value.
I tried to simulate input in more sophisticated ways, like triggering keyboard events or third party tools, but with no success. It looks like any programmatic way to change the input's value, is not limited by maxlength.
I know this is an old question, but this may be helpful to someone with the same problem.
In my case I just checked the the value length of the input manually, in the function used to set the input value:
function insertKey(input: HTMLInputElement, key: string) {
input.dispatchEvent(new KeyboardEvent('keydown', {key: key}));
if (input.value.length < input.maxLength) {
input.value += key;
input.dispatchEvent(new KeyboardEvent('change', null));
}
input.dispatchEvent(new KeyboardEvent('keyup', {key: key}));
}

Resources