نوشتن اعتبارسنجهای سفارشی برای فرمهای مبتنی بر قالبها در Angular
نویسنده: وحید نصیری
تاریخ: ۱۳۹۶/۰۴/۱۴ ۲۰:۴۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
>ng g m CustomValidators -m app.module --routing
>ng g c CustomValidators/user-register
>ng g cl CustomValidators/user
export class User {
constructor(
public username: string = "",
public email: string = "",
public password: string = "",
public confirmPassword: string = ""
) {}
}
>ng g d CustomValidators/EmailValidator -m custom-validators.module
import { Directive } from "@angular/core";
import { AbstractControl, NG_VALIDATORS, Validator } from "@angular/forms";
@Directive({
selector:
"[appEmailValidator][formControlName],[appEmailValidator][formControl],[appEmailValidator][ngModel]",
providers: [
{
provide: NG_VALIDATORS,
useExisting: EmailValidatorDirective,
multi: true
}
]
})
export class EmailValidatorDirective implements Validator {
validate(element: AbstractControl): { [key: string]: any } {
const emailRegex = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
const valid = emailRegex.test(element.value);
return valid ? null : { appEmailValidator: true };
}
} <input #email="ngModel" required appEmailValidator type="text" class="form-control" name="email" [(ngModel)]="model.email">
selector: "[appEmailValidator][formControlName],[appEmailValidator][formControl],[appEmailValidator][ngModel]",
"apps": [
{
// ...
"prefix": "app", selector: "[appEmailValidator]"
providers: [
{
provide: NG_VALIDATORS,
useExisting: EmailValidatorDirective,
multi: true
} export class EmailValidatorDirective implements Validator { validate(element: AbstractControl): { [key: string]: any } validate(element: AbstractControl): { [key: string]: any } {
const emailRegex = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
const valid = emailRegex.test(element.value);
return valid ? null : { appEmailValidator: true };
} <input #email="ngModel" required appEmailValidator type="text" class="form-control" name="email" [(ngModel)]="model.email">
{ required:true } { minlength : {
requiredLength : 3,
actualLength : 1
}
} { appEmailValidator: true } <div class="alert alert-danger" *ngIf="email.errors.appEmailValidator"> The entered email is not valid. </div>
public password: string = "", public confirmPassword: string = ""
>ng g d CustomValidators/EqualValidator -m custom-validators.module
import { Directive, Attribute } from "@angular/core";
import { Validator, AbstractControl, NG_VALIDATORS } from "@angular/forms";
@Directive({
selector:
"[appValidateEqual][formControlName],[appValidateEqual][formControl],[appValidateEqual][ngModel]",
providers: [
{
provide: NG_VALIDATORS,
useExisting: EqualValidatorDirective,
multi: true
}
]
})
export class EqualValidatorDirective implements Validator {
constructor(@Attribute("compare-to") public compareToControl: string) {}
validate(element: AbstractControl): { [key: string]: any } {
const selfValue = element.value;
const otherControl = element.root.get(this.compareToControl);
console.log("EqualValidatorDirective", {
thisControlValue: selfValue,
otherControlValue: otherControl ? otherControl.value : null
});
if (otherControl && selfValue !== otherControl.value) {
return {
appValidateEqual: true // Or a string such as 'Password mismatch.' or an abject.
};
}
if (
otherControl &&
otherControl.errors &&
selfValue === otherControl.value
) {
delete otherControl.errors["appValidateEqual"];
if (!Object.keys(otherControl.errors).length) {
otherControl.setErrors(null);
}
}
return null;
}
} export class EqualValidatorDirective implements Validator {
constructor(@Attribute("compare-to") public compareToControl: string) {} <input #password="ngModel" required type="password" class="form-control" appValidateEqual compare-to="confirmPassword" name="password" [(ngModel)]="model.password">
export class EqualValidatorDirective implements Validator {
constructor(@Attribute("compare-to") public compareToControl: string) {}
validate(element: AbstractControl): { [key: string]: any } {
const selfValue = element.value;
const otherControl = element.root.get(this.compareToControl);
console.log("EqualValidatorDirective", {
thisControlValue: selfValue,
otherControlValue: otherControl ? otherControl.value : null
}); if (otherControl && selfValue !== otherControl.value) {
return {
appValidateEqual: true // Or a string such as 'Password mismatch.' or an abject.
};
} if (otherControl && otherControl.errors && selfValue === otherControl.value) {
delete otherControl.errors["appValidateEqual"];
if (!Object.keys(otherControl.errors).length) {
otherControl.setErrors(null);
}
}
return null; import { NgForm } from "@angular/forms";
import { User } from "./../user";
import { Component, OnInit } from "@angular/core";
@Component({
selector: "app-user-register",
templateUrl: "./user-register.component.html",
styleUrls: ["./user-register.component.css"]
})
export class UserRegisterComponent implements OnInit {
model = new User();
constructor() {}
ngOnInit() {}
submitForm(form: NgForm) {
console.log(this.model);
console.log(form.value);
}
} <div class="container"> <h3>Registration Form</h3> <form #form="ngForm" (submit)="submitForm(form)" novalidate>
<div class="form-group" [class.has-error]="username.invalid && username.touched">
<label class="control-label">User Name</label>
<input #username="ngModel" required maxlength="8" minlength="4" type="text"
class="form-control" name="username" [(ngModel)]="model.username">
<div *ngIf="username.invalid && username.touched">
<div class="alert alert-info">
errors: {{ username.errors | json }}
</div>
<div class="alert alert-danger" *ngIf="username.errors.required">
username is required.
</div>
<div class="alert alert-danger" *ngIf="username.errors.minlength">
username should be minimum {{username.errors.minlength.requiredLength}} characters.
</div>
<div class="alert alert-danger" *ngIf="username.errors.maxlength">
username should be max {{username.errors.maxlength.requiredLength}} characters.
</div>
</div>
</div>
<div class="form-group" [class.has-error]="email.invalid && email.touched">
<label class="control-label">Email</label>
<input #email="ngModel" required appEmailValidator type="text" class="form-control"
name="email" [(ngModel)]="model.email">
<div *ngIf="email.invalid && email.touched">
<div class="alert alert-info">
errors: {{ email.errors | json }}
</div>
<div class="alert alert-danger" *ngIf="email.errors.required">
email is required.
</div>
<div class="alert alert-danger" *ngIf="email.errors.appEmailValidator">
The entered email is not valid.
</div>
</div>
</div>
<div class="form-group" [class.has-error]="password.invalid && password.touched">
<label class="control-label">Password</label>
<input #password="ngModel" required type="password" class="form-control"
appValidateEqual compare-to="confirmPassword" name="password" [(ngModel)]="model.password">
<div *ngIf="password.invalid && password.touched">
<div class="alert alert-info">
errors: {{ password.errors | json }}
</div>
<div class="alert alert-danger" *ngIf="password.errors.required">
password is required.
</div>
<div class="alert alert-danger" *ngIf="password.errors.appValidateEqual">
Password mismatch. Please complete the confirmPassword .
</div>
</div>
</div>
<div class="form-group" [class.has-error]="confirmPassword.invalid && confirmPassword.touched">
<label class="control-label">Retype password</label>
<input #confirmPassword="ngModel" required type="password" class="form-control"
appValidateEqual compare-to="password" name="confirmPassword" [(ngModel)]="model.confirmPassword">
<div *ngIf="confirmPassword.invalid && confirmPassword.touched">
<div class="alert alert-info">
errors: {{ confirmPassword.errors | json }}
</div>
<div class="alert alert-danger" *ngIf="confirmPassword.errors.required">
confirmPassword is required.
</div>
<div class="alert alert-danger" *ngIf="confirmPassword.errors.appValidateEqual">
Password mismatch.
</div>
</div>
</div>
<button class="btn btn-primary" [disabled]="form.invalid" type="submit">Ok</button> </form> </div>
>npm install >ng build --watch
>dotnet restore >dotnet watch run
[RegularExpression(@"^[\u0600-\u06FF,\u0590-\u05FF,0-9\s]*$",
ErrorMessage = "لطفا تنها از اعداد و حروف فارسی استفاده نمائید")]
public string FriendlyName { get; set; } export class EqualValidatorDirective implements Validator {
constructor(@Attribute("compare-to") public compareToControl: string) {} export class EqualValidatorDirective implements Validator {
constructor() {}
@Input('compare-to') compareToControl: string;
///...
}