[英]Angular5 Custom Validators for Reactive forms
我在為Angular v5應用程序制作自定義驗證程序時遇到問題。 在文檔中僅遵循基本密碼匹配示例的文檔進行操作,但未通過驗證。
this.personalInfoForm = _fb.group({
'name': [null,Validators.minLength(7)],
'email': [null, CustomValidators.emailOrEmpty],
'password':[null],
'password_confirm': [null]
}, this.passwordMatch);
//EDIT
passwordMatch(g: FormGroup) {
return g.get('password').value === g.get('password_confirm').value ? null : {'mismatch': true};
}
另外,如何使用動態輸入名稱的功能? 這樣我就可以將其用於電子郵件等。例如:match('inputToMatch');
編輯:添加HTML
<form class="col-lg-12" [formGroup]="personalInfoForm" (ngSubmit)="updatePersonalSettings(personalInfoForm.value)">
<h4>Basic Information</h4>
<div class="form-group row ">
<label for="name" class="col-sm-2 col-form-label">Full Name</label>
<div class="col-sm-6">
<input
type="text"
class="form-control"
id="name"
placeholder="{{currentUser.name}}"
formControlName="name"
/>
</div>
</div>
<div class="form-group row">
<label for="email" class="col-sm-2 col-form-label">Email Address</label>
<div class="col-sm-6">
<input
type="email"
class="form-control"
id="email"
placeholder="{{currentUser.email}}"
formControlName="email"
value=" ">
</div>
</div>
<h4>Password</h4>
<div class="form-group row">
<label for="password" class="col-sm-2 col-form-label">Password</label>
<div class="col-sm-6">
<input
type="password"
class="form-control"
id="password"
formControlName="password"
placeholder="password">
</div>
</div>
<div class="form-group row">
<label for="password_confirm" class="col-sm-2 col-form-label">Confirm Password</label>
<div class="col-sm-6">
<input
type="email"
class="form-control"
id="password_confirm"
formControlName="password_confirm"
placeholder="password confirmation" >
</div>
</div>
<br>
<button [disabled]="!personalInfoForm.valid || !personalInfoForm.dirty" type="submit" class="btn btn-primary">Save</button>
工作:但是如何傳遞參數,以便可以將相同的方法用於不同的輸入名稱。
passwordMatch(control: AbstractControl) {
const password = control.root.get('password');
const confirm = control.value;
if (!password || !confirm) return null;
return password.value === confirm ? null : { nomatch: true };
}
我想我做了你想要的。 該代碼是為PrimeNG准備的,但是大多數情況下,您只需要替換一些css類即可使其進行引導或其他所需的操作。
它是用於驗證必填字段,最小長度,模式和自定義驗證的組件。 首先,有關如何使用的示例:
示例1:驗證:必填,最小長度和模式。
some.component.html
<input pInputText type="text" name="email" [(ngModel)]="user.email"
ngModel #email="ngModel" required minlength="5"
pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$">
<app-input-validation [control]="email"
[errDef]="{ required: 'A email is required',
pattern: 'Enter a valid email address',
minlength: 'The email should be at least 5 characteres'}" >
</app-input-validation>
示例2:驗證:必填,minlength和自定義函數。
some.component.html
<input pInputText type="text" name="name" [(ngModel)]="user.name"
ngModel #name="ngModel" required minlength="5">
<app-input-validation [control]="name" [custom]="validateField1"
[errDef]="{ required: 'A name is required',
custom: 'Name must be diferent from sysadm',
minlength: 'The name should be at least 5 characteres'}" >
</app-input-validation>
some.component.ts
...
// This validation funcion is called by the parâmeter [custom]="validateField1"
// and the component receive the field as argument.
validateField1(context: NgModel ): boolean {
if ( context.control.value === 'sysadm') {
return false;
}
return true;
...
示例3:驗證:必填,minlength和包含2個字段的自定義函數。 some.component.html
...
<form #f="ngForm" autocomplete="off" (ngSubmit)="save(f)">
...
<div class="ui-md-6 ui-g-12 ui-fluid">
<label>Password</label>
<input pPassword type="password" name="password"
[(ngModel)]="user.password"
ngModel #password="ngModel" required minlength="5" >
</div>
<div class="ui-md-6 ui-g-12 ui-fluid">
<label>Retype Password</label>
<input pPassword type="password" name="repassword"
[(ngModel)]="user.repassword" required minlength="5" >
</div>
<!-- the parameter [form]="f" must be passed to app-input-validation
because the validatePassword must use 2 fields from the form -->
....
<app-input-validation [control]="password" [custom]="validatePassword"
[form]="f"
[errDef]=
"{ required: 'A password is required',
custom: 'Both passwords must match.',
minlength: 'The email should be at least 5 characteres'}" >
</app-input-validation>
</div>
some.component.ts
...
validatePassword(context: NgForm ): boolean {
if ( context.form.value.password === context.form.value.repassword ) {
return true;
}
return false;
}
...
如果滿足您的需要,代碼為:
輸入驗證.component.ts
import { FormControl } from '@angular/forms';
import { Component, OnInit, Input } from '@angular/core';
import { NgModel, NgForm } from '@angular/forms';
@Component({
selector: 'app-input-validation',
template: `
<div *ngIf="hasError()" class="ui-message ui-messages-error">
{{ errorMessage }}
</div>
`,
styles: [`
.ui-messages-error {
margin: 0;
margin-top: 4px;
}
`]
})
export class InputValidationComponent {
@Input() control: NgModel;
@Input() form: NgForm;
@Input() errDef: any;
@Input() custom: any;
errorMessages = [];
errorMessage = '';
hasError(): boolean {
this.errorMessages = [];
this.errorMessage = '';
if ( this.errDef && ( this.control.errors || this.errDef['custom'] ) ) {
Object.keys(this.errDef).some(key => {
if ( this.control.errors && this.control.errors[key]) {
this.errorMessages.push(this.errDef[key]);
} else if ( key === 'custom' && !this.runCustom() ) {
this.errorMessages.push(this.errDef[key]);
}
return false;
});
}
for ( const m of this.errorMessages ){
if ( this.errorMessage.length > 0 ) {
this.errorMessage = this.errorMessage + '. ';
}
this.errorMessage = this.errorMessage + m;
}
return this.errorMessages.length > 0 && this.control.dirty;
}
public runCustom(): boolean {
return this.custom(this);
}
}
就是這樣。 希望對您有所幫助。 https://gist.github.com/sannonaragao/dbf747676016ed0c4054f8abd2e2a4d2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.