[英]Angular Material Mat-error Showing error for valid inputs, while validating with regex
使用 angular 材料创建注册表单,即使没有错误也会显示错误。
对于有效输入,它显示错误无效输入。 我已经删除了输入数据时该字段变为红色的 mat-error 条件。
控件内的状态显示该字段在提交时有效。
错误条件在全局常量文件中。 -全局常量
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)]],
请协助您的专业知识。
请检查以下代码
输入错误状态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]+'),
],
],
});
}
}
输入错误状态匹配器。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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.