Password Validation error in Angular Reactive Form Validator - javascript

Using Angular Reactive Form to validate password which as to match Password with atleast :
|*> 1 lowercase
|*> 1 uppercase
|*> 1 numeric
|*> 8 char longer
Using Reg Exp :
"^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})"
Html Code :
<form [formGroup]="NamFomNgs">
<label>Email :
<input type="email" name="MylHtm" formControlName="MylNgs">
</label><br>
<div class="ErrMsgCls" *ngIf="(NamFomNgs.controls['MylNgs'].touched || NamFomNgs.controls['MylNgs'].dirty) &&
!NamFomNgs.controls['MylNgs'].valid">
<span *ngIf="NamFomNgs.controls['MylNgs'].errors.required">This field is required</span>
<span *ngIf="NamFomNgs.controls['MylNgs'].errors.email">Enter valid email</span>
</div><br>
<label>Password :
<input type="text" name="PwdHtm" formControlName="PwdNgs">
</label><br>
<div class="ErrMsgCls" *ngIf="(NamFomNgs.controls['PwdNgs'].touched || NamFomNgs.controls['PwdNgs'].dirty) &&
!NamFomNgs.controls['PwdNgs'].valid">
<span *ngIf="NamFomNgs.controls['PwdNgs'].errors.required">This field is required</span>
<span *ngIf="NamFomNgs.controls['PwdNgs'].errors.pattern">Enter valid password</span>
</div><br>
<button [disabled]="!NamFomNgs.valid">Submit</button>
</form>
TypeScript Code :
NamFomNgs:FormGroup;
constructor(private NavPkjVaj: ActivatedRoute, private HtpCncMgrVaj: HttpClient,private FomNgsPkjVaj: FormBuilder){
this.NamFomNgs = FomNgsPkjVaj.group(
{
MylNgs:[null,Validators.compose([
Validators.required,
Validators.email ])],
PwdNgs:[null,Validators.compose([
Validators.required,
Validators.pattern("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})")])]
});
}
Screen Shot of Output :
When I try with https://regex101.com/
The same reg exp shows valid for the requirments. But its invalid in Angular. Kindly help me with right way and to resolve this.

You have to capture something in your regex, you're only using positive look-ahead groups. Just change the length part like this :
"^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{8,}"

Related

angular reactive pattern for only numbers with + and #

I'm working on reactive form with postal code control it allows only + and # only with numbers. Max length for the controls is 10. I tried with following code even i enter the valid value it still shows the error.
ts
postalCode: ['', {
validators: [
Validators.required,
Validators.pattern('/^(?=.*[0-9])[+#()0-9]+$/')
],
updateOn: 'blur'
}],
View
<input type="text"
class="form-control"
id="postalCode"
formControlName="postalCode"
maxlength="10">
<div class="error-msg"
*ngIf="driverForm.controls.postalCode.hasError('pattern')">
<span class="red-star"> patter Error </span>
</div>
Remove quotes from regex
Instead of
'/^(?=.*[0-9])[+#()0-9]+$/'
Use without ' quotes
/^(?=.*[0-9])[+#()0-9]+$/

type number and pattern not showing error label

I want to have a field in which users can type only numbers 0-9. In case they type other characters like '.' or 'e' it has to show an error that only positive natural numbers are allowed. Form is used in Angular.
So I have here the html form:
<div class="col-xl-8">
<input formControlName="money" type="number" class="form-control">
<span class="error" *ngIf="money?.errors?.pattern"> Natural numbers </span>
</div>
while pattern is
this.money = new FormControl('', [Validators.required, Validators.pattern('^[1-9][0-9]*$')]);
The pattern is just fine it allows numbers from 0 till 9 and it doesn't allow decimals or '.' or 'e'.
So the problem is that since input is type number it allows '.' and 'e' even though the pattern doesn't allow it and I can't submit it, the error message is not showed since the html validater is based on the type number thing.
Yet, inputs such as these are allowed and the error label does not appear:
1.....2
......
eeee........
1.0.0.01.0
And so on.
So what should I do to show the error label when '.' or 'e' are typed?
Use ng-pattern directive directly?
<div class="col-xl-8">
<input formControlName="money"
type="number"
ng-pattern="^[1-9][0-9]*$')]"
class="form-control">
<span class="error" *ngIf="money?.errors?.pattern"> Natural numbers </span>
</div>
And tie validation to $valid of that input myForm.myInput.$valid
Use following code:
<div class="col-xl-8">
<input [formControl]="money"
type="number"
class="form-control">
<span class="error" *ngIf="money.dirty && money?.errors?.pattern"> Natural numbers </span>
</div>
In your ts file update regex ^[1-9][0-9]{1,3}
Hope it will help
In .ts file :
export class ReactiveFormExampleComponent{
reactiveForm: FormGroup;
constructor(private fb: FormBuilder) {
this.reactiveForm = fb.group({
money: ['', [Validators.required, Validators.pattern('^[1-9][0-9]*$')]]
});
}
onSubmit() {
alert("Form submitted");
}
}
html file
<form [formGroup]="reactiveForm" (ngSubmit)="onSubmit()" nonvalidate>
<div>
<label class="center-block">Money:
<input type="number" class="form-control" formControlName="money">
</label>
<span [hidden]="reactiveForm.controls.money.valid || reactiveForm.controls.money.pristine" class="errorMsg">Natural numbers only</span>
</div>
<button type="submit" [disabled]="reactiveForm.invalid" class="btn btn-success">Save</button>
</form>
NOTE : Don't forget to import 'ReactiveFormsModule' in NgModule.
Here is working plunker check it out here.

Validating Same Password Input Angular 2/4 - ERROR Cannot find control with unspecified name attribute

I'm trying to validate that the password and ConfirmPassword fields are the same in my form, but when I add the validation provided by other posts on SO (aside from changing ControlGroup to FormGroup) I keep getting
ERROR: Cannot find control with unspecified name attribute
BUT, when I don't validate using the "matchingPassword" group below and just use the Validators.required syntax, it works just fine.
I don't know why it's throwing that error. Has anyone else worked through this? I'm currently building on Angular 4 Distro.
constructor(
private accountService: accountService,
fb: FormBuilder,
) {
this.changePWForm = fb.group({
'CurrentPassword' : [null, Validators.required],
'SecurityQuestions' : [null, Validators.required],
'SecurityQuestionAnswer' : [null, Validators.required],
'matchingPassword': fb.group({
'NewPassword' : [null, Validators.compose([Validators.pattern(this.strongPW), Validators.required])],
'ConfirmPassword' : [{disabled: true}, Validators.required],
}, {validator: this.equalPasswords})
})
}
equalPasswords(group: FormGroup){
//When I use the syntax above, it never makes it here.
var valid = false;
for (var name in group.controls) {
var val = group.controls[name].value
}
if (valid) {
return null;
}
return {
areEqual: true
};
}
Here's My HTML Template
<form [formGroup]="changePWForm" (ngSubmit)="updatePW(changePWForm.value)" *ngIf="securityQuestions">
<div class="form-group">
<label>Current Password:</label>
<input type="text" [(ngModel)]="changePWData.CurrentPassword" [formControl]="changePWForm.controls['CurrentPassword']">
</div>
<div class="form-group">
<label>New Password:</label>
<input type="text" [(ngModel)]="changePWData.NewPassword" [formControl]="changePWForm.controls['NewPassword']">
<small *ngIf="!changePWForm.controls.NewPassword.valid && !changePWForm.controls.NewPassword.pristine">You need a secure password.</small>
</div>
<div class="form-group" >
<label>Confirm New Password:</label>
<input type="text" [(ngModel)]="changePWData.ConfirmPassword" [formControl]="changePWForm.controls['ConfirmPassword']">
</div>
<div class="form-group">
<label>Security Question:</label>
<select #select type="text" [(ngModel)]="selectedSecurityQuestion" [formControl]="changePWForm.controls['SecurityQuestions']" class="select">
<option *ngFor="let question of securityQuestions" [ngValue]="question">{{question.SecurityQuestionText}}</option>
</select>
</div>
<div class="form-group">
<label>Security Question Answer: </label>
<input type="text" [(ngModel)]="securityQuestionAnswer" [formControl]="changePWForm.controls['SecurityQuestionAnswer']">
</div>
<div *ngIf="processing">
<div class="spinner">
<div class="rect1"></div>
<div class="rect2"></div>
<div class="rect3"></div>
<div class="rect4"></div>
<div class="rect5"></div>
</div>
</div>
<button *ngIf="!processing" type="submit" [disabled]="!changePWForm.valid">Change Address</button>
</form>
The problem is that you've a nested FormGroup (matchingPassword).
So, you must wrap the controls of this nested group using a <div>, for example.
Wrap your password controls (NewPassword and ConfirmPassword) in a element, like this:
<form [formGroup]="changePWForm" ...>
...
<div formGroupName="matchingPassword">
<!-- you can also use [formGroup] if you want -->
<!-- Put the content of password controls here -->
</div>
...
</form>
Besides having the problem stated by developer033, that you are missing the formGroupName:
<div formGroupName="matchingPassword">
<!-- you can also use [formGroup] if you want -->
<!-- Put the content of password controls here -->
</div>
.. I also didn't really understand the custom validator and it didn't function correctly for me. Also noticed for some reason the validator don't even fire when marking form controls like:
[formControl]="changePWForm.controls['NewPassword']"
I can't really say why, but I also prefer the more "cleaner" version:
formControlName="NewPassword"
So changing those would make the custom validator fire.
Then to the custom validator, this is the way I do it. Also notice I've changed areEqual: true to notEqual:true to better describe what is actually going on, since when we return null it means that the passwords match, and if we return something else than null, it means that we want to mark that the passwords do not match.
equalPasswords = (control: AbstractControl): {[key: string]: boolean} =>{
const newPassword = control.get('NewPassword');
const confirmPassword = control.get('ConfirmPassword');
if (!newPassword || !confirmPassword) {
return null;
}
return newPassword.value === confirmPassword.value ? null : { notEqual: true };
}
Here's a DEMO with a shortened version of your code.

How to validate specific email address using ng-pattern?

I have email validation that has specific format ab123c#email.com or ab1234#email.com its validationg first 5 characters but not the complete email address using angularjs ng-pattern. How can i validate specific email address using angularjs ?
main.html
<div layout="row">
<md-input-container flex="100">
<label>Cc</label>
<input type="email" name="email" ng-model="notifyCtrl.cc" ng-list="," ng-pattern="pattern(user.type)">
<div class="help-block" ng-messages="notifyForm.email.$error" ng-show="notifyForm.email.$touched && notifyForm.email.$invalid">
<div ng-if="user.type === 'notify'">
<div ng-message="pattern">
An email name must only contain a-z, A-Z, 0-9, or _ characters.(ie. ab123c#tad.com, ab1234#tad.com
</div>
</div>
</div>
</md-input-container>
</div>
ctrl.js
var emailFormat = new RegExp('^[a-z]{2}[0-9]{3}[a-z0-9]$');
$scope.pattern = function(type){
if(type === 'notify') {
return emailFormat;
}
};
In your Input email you can use the following ng-pattern
ng-pattern="/^[_a-z0-9]+(\.[_a-z0-9]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/"
This is the best pattern to check valid email address:
ng-pattern='/^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/'
You can try this another regex:
ng-pattern='/^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}#)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*#(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-+[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-+[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$/';

ng-change doesn't trigger on number input type

I am using angularJS, and I'm trying to get an error to pop up if the input value is not a number.
Number Value: <input type="number" ng-model="mydata.number" ng-change="checkNumber()" />
<p style="color:red" ng-show="numberError">
{{ numberError }}
</p>
And then inside $scope.checkNumber I check to see if it's NaN:
if(!$scope.mydata.number || isNaN($scope.mydata.number)) {
$scope.numberError = "This must be a number";
}
It appears that when I initially enter a string such as "fff" no error popups up, and we don't enter the checkNumber function, but if I enter "1fff" then it does enter the function and the error shows like it should.
If the input type is number and the initial character is not a number, does the ng-model not change?
What about using the Angular built-in validation, like this:
<form name="myForm">
Number Value:
<input type="number" ng-model="mydata.number" name="myNumber" />
<p style="color:red" ng-show="myForm.myNumber.$dirty && !myForm.myNumber.$valid">
{{ numberError }}
</p>
</form>

Categories

Resources