使用 Angular Material 创建注册表单,即使没有错误也会显示错误。
对于有效输入,它会显示错误“无效输入”。 我已经删除了输入数据时字段变为红色的 mat-error 条件。
控件内的状态显示该字段在提交时有效。
错误条件位于全局常量文件中。 -全局常量ts
export class globalConstants{
public static genericErr:string="Someting wnet wrong,Please try again";
public static usrname:string='[a-zA-Z0-9 ]*';
}
HTML-
<mat-form-field appearance="fill" fxFlex>
<mat-label>User Name</mat-label>
<input matInput formControlName="usrname" required>
<mat-error *ngif="signUpForm.controls.usrname.touched && signUpForm.controls.usrename.invalid">
<span *ngIf="signUpForm.controls.usrname.errors.required">User Name is Mandatory</span>
<span *ngIf="signUpForm.controls.usrname.errors.pattern">Ivalid Input</span>
</mat-error>
</mat-form-field>}
注册 Ts 文件:
import { globalConstants } from '../shared/globalConst';
signUpForm: any = FormGroup;
ngOnInit(): void {
this.signUpForm = this.formBuilder.group({usrname: ['Enter Username', [Validators.required, Validators.pattern(globalConstants.usrname)]],
请利用您的专业知识提供帮助。
最佳答案
请检查以下代码
input-error-state-matcher.ts
import { Component } from '@angular/core';
import {
FormGroup,
FormBuilder,
FormControl,
FormGroupDirective,
NgForm,
Validators,
} from '@angular/forms';
/** @title Input with a custom ErrorStateMatcher */
@Component({
selector: 'input-error-state-matcher-example',
templateUrl: './input-error-state-matcher-example.html',
styleUrls: ['./input-error-state-matcher-example.css'],
})
export class InputErrorStateMatcherExample {
userAddressValidations: FormGroup;
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.userAddressValidations = this.formBuilder.group({
firstName: [
'',
[
Validators.required,
Validators.minLength(4),
Validators.maxLength(20),
Validators.pattern('[a-zA-Z]+'),
],
],
});
}
}
input-error-state-matcher.html
<form class="example-form" [formGroup]="userAddressValidations">
<mat-form-field class="example-full-width">
<input matInput placeholder="First Name" formControlName="firstName">
<mat-error *ngIf="userAddressValidations.get('firstName').hasError('required')">
First Name is Required!
</mat-error>
<mat-error *ngIf="userAddressValidations.get('firstName').hasError('minlength')">
First Name should be atleast 4 characters long!
</mat-error>
<mat-error *ngIf="userAddressValidations.get('firstName').hasError('maxlength')">
First Name can be atmax n characters long!
</mat-error>
<mat-error *ngIf="userAddressValidations.get('firstName').hasError('pattern')">
First Name must follow this pattern!
</mat-error>
</mat-form-field>
</form>
关于javascript - Angular Material Mat-error 在使用正则表达式进行验证时显示有效输入的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73538136/