我想编写可以以任何角度形式使用的通用验证 - 正常反应已经完成并且工作正常
Posted
技术标签:
【中文标题】我想编写可以以任何角度形式使用的通用验证 - 正常反应已经完成并且工作正常【英文标题】:I want to write generic validation that i can use in any angular form - normal reactive is already done and working fine 【发布时间】:2020-03-12 00:06:03 【问题描述】:。任何人都可以解决这个问题。
import Component from '@angular/core';
import FormBuilder, FormGroup, Validators from '@angular/forms';
// import custom validator to validate that password and confirm password fields match
import MustMatch from './_helpers/must-match.validator';
@Component(
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
)
export class AppComponent
title = 'val';
registerForm: FormGroup;
submitted = false;
constructor(private formBuilder: FormBuilder)
ngOnInit()
this.registerForm = this.formBuilder.group(
title: ['', Validators.required],
firstName: ['', Validators.required],
lastName: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required, Validators.minLength(6)]],
confirmPassword: ['', Validators.required],
acceptTerms: [false, Validators.requiredTrue]
,
validator: MustMatch('password', 'confirmPassword')
);
get f() return this.registerForm.controls;
onSubmit()
this.submitted = true;
// stop here if form is invalid
if (this.registerForm.invalid)
return;
// display form values on success
alert('SUCCESS!! :-)\n\n' + JSON.stringify(this.registerForm.value, null, 4));
onReset()
this.submitted = false;
this.registerForm.reset();
<!-- language: lang-html -->
<div class="card m-3">
<h5 class="card-header">Form Validation</h5>
<div class="card-body">
<form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
<div class="form-row">
<div class="form-group col">
<label>Title</label>
<select formControlName="title" class="form-control" [ngClass]=" 'is-invalid': submitted && f.title.errors ">
<option value=""></option>
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="Miss">Miss</option>
<option value="Ms">Ms</option>
</select>
<div *ngIf="submitted && f.title.errors" class="invalid-feedback">
<div *ngIf="f.title.errors.required">Title is required</div>
</div>
</div>
<div class="form-group col-5">
<label>First Name</label>
<input type="text" formControlName="firstName" class="form-control" [ngClass]=" 'is-invalid': submitted && f.firstName.errors " />
<div *ngIf="submitted && f.firstName.errors" class="invalid-feedback">
<div *ngIf="f.firstName.errors.required">First Name is required</div>
</div>
</div>
<div class="form-group col-5">
<label>Last Name</label>
<input type="text" formControlName="lastName" class="form-control" [ngClass]=" 'is-invalid': submitted && f.lastName.errors " />
<div *ngIf="submitted && f.lastName.errors" class="invalid-feedback">
<div *ngIf="f.lastName.errors.required">Last Name is required</div>
</div>
</div>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" formControlName="email" class="form-control" [ngClass]=" 'is-invalid': submitted && f.email.errors " />
<div *ngIf="submitted && f.email.errors" class="invalid-feedback">
<div *ngIf="f.email.errors.required">Email is required</div>
<div *ngIf="f.email.errors.email">Email must be a valid email address</div>
</div>
</div>
<div class="form-row">
<div class="form-group col">
<label>Password</label>
<input type="password" formControlName="password" class="form-control" [ngClass]=" 'is-invalid': submitted && f.password.errors " />
<div *ngIf="submitted && f.password.errors" class="invalid-feedback">
<div *ngIf="f.password.errors.required">Password is required</div>
<div *ngIf="f.password.errors.minlength">Password must be at least 6 characters</div>
</div>
</div>
<div class="form-group col">
<label>Confirm Password</label>
<input type="password" formControlName="confirmPassword" class="form-control" [ngClass]=" 'is-invalid': submitted && f.confirmPassword.errors " />
<div *ngIf="submitted && f.confirmPassword.errors" class="invalid-feedback">
<div *ngIf="f.confirmPassword.errors.required">Confirm Password is required</div>
<div *ngIf="f.confirmPassword.errors.mustMatch">Passwords must match</div>
</div>
</div>
</div>
<div class="form-group form-check">
<input type="checkbox" formControlName="acceptTerms" id="acceptTerms" class="form-check-input" [ngClass]=" 'is-invalid': submitted && f.acceptTerms.errors " />
<label for="acceptTerms" class="form-check-label">Accept Terms & Conditions</label>
<div *ngIf="submitted && f.acceptTerms.errors" class="invalid-feedback">Accept Ts & Cs is required</div>
</div>
<div class="text-center">
<button class="btn btn-primary mr-1">Register</button>
<button class="btn btn-secondary" type="reset" (click)="onReset()">Cancel</button>
</div>
</form>
</div>
</div>
【问题讨论】:
这个“通用验证器”会做什么? 通用验证,我可以在我的应用程序的每种形式中使用,就像现在这只有一种应用程序形式,如果假设我在应用程序中有 10 个表单,我可以将验证作为指令导入并在' N ' 表格数量。 好的,但问题仍然存在,这个验证器应该做什么?验证者可以做不同的事情。但是,例如,如果您想比较两个值,则只需将表单控件传递给验证器,由验证器进行检查。所以你有一个“通用”验证器。 顺便说一句,您似乎已经有了一个“通用”验证器,因为您将 formcontrolnames 传递给您的自定义验证器,所以我不知道您的期望。 【参考方案1】:所以,您可以使用 AbstractControl 进行自定义验证
url.validator.ts:
import AbstractControl from '@angular/forms';
export function ValidateUrl(control: AbstractControl)
if (!control.value.startsWith('https') || !control.value.includes('.io'))
return validUrl: true ;
return null;
app.component.ts:
import Component, OnInit from '@angular/core';
import FormBuilder, FormControl, FormGroup, Validators from '@angular/forms';
import ValidateUrl from './validators/url.validator';
@Component(
// ...
)
export class AppComponent implements OnInit
myForm: FormGroup;
constructor(private fb: FormBuilder)
ngOnInit()
this.myForm = this.fb.group(
userName: ['', Validators.required],
websiteUrl: ['', [Validators.required, ValidateUrl]],
);
更多信息请查看链接:alligator.io/angular/reactive-forms-custom-validator
【讨论】:
你好 Safwan,谢谢它对我有用,但我还想知道一件事 - 如何在其中添加模式...我想使用只允许字母而不是数字的模式,例如---- - 模式=“[a-zA-Z]*” 我如何检查用户只输入字母而不是数字 url.validator.ts import AbstractControl from '@angular/forms'; const alphabetic = '[a-zA-Z ]*' 导出函数 ValidateEmail(control: AbstractControl) if (!control.value.alphabetic) return validEmail: true ; 返回空值; - form.html 电子邮件是必需的 app.component.ts 首先,您可以使用控件属性(control.value)访问输入的数据。 然后,为了验证输入的数据,您可以使用正则表达式,并将您的模式作为属性传递给该正则表达式,您将实现您的目标 嗨尼克,好吧,我会给你两行代码,在第一行我创建了一个新的正则表达式(正则表达式)实例来检查输入的字符串是否兼容,并且在第二行我应用了正则表达式,所以当且仅当匹配我们的模式时才会返回 true let regex = new RegExp('^[a-zA-Z]+$') console.log(regex.test(control.value)) ;以上是关于我想编写可以以任何角度形式使用的通用验证 - 正常反应已经完成并且工作正常的主要内容,如果未能解决你的问题,请参考以下文章