[英]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.