[英]Why my min and max validation is not firing?
I have the template like below:我有如下模板:
<form class="form" [formGroup]="configWeightage">
<div class="example-container">
Enter value in between 0 to 100 <mat-form-field>
<input
matInput
type="number"
min="0"
max="100"
class="example-right-align"
[formControlName]="weightageValue"
id="weightage"
required
/>
</mat-form-field>
<mat-error *ngIf="weightageValue.hasError('min(0)')" style="color: red"
>Please enter greater than 0</mat-error
>
<mat-error *ngIf="weightageValue.hasError('max(100)')" style="color: red"
>Please enter less than 100</mat-error
>
</div>
</form>
This is the class file这是 class 文件
import { Component } from '@angular/core';
import { FormBuilder,FormGroup, Validators,FormControl } from '@angular/forms';
/** @title Form field with prefix & suffix */
@Component({
selector: 'form-field-prefix-suffix-example',
templateUrl: 'form-field-prefix-suffix-example.html',
styleUrls: ['form-field-prefix-suffix-example.css'],
})
export class FormFieldPrefixSuffixExample {
configWeightage:FormGroup;
formBuilder : FormBuilder;
weightageValueControl = new FormControl(['',Validators.required,Validators.min(0),Validators.max(100)]);
hide = true;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.configWeightage = this.formBuilder.group(
{
'weightageValue' :this.weightageValueControl
}
)
}
}
I am supposed the fire the error when there is a value NOT in between 0 and 100当值不在 0 到 100 之间时,我应该会触发错误
But no validation message will be fired但是不会触发任何验证消息
Here is the stack bliz code for the same, so that you can run and fix yourself.这是相同的堆栈 bliz 代码,以便您可以自己运行和修复。
https://stackblitz.com/edit/angular-mat-form-field-dq8ntd?file=app/form-field-prefix-suffix-example.html https://stackblitz.com/edit/angular-mat-form-field-dq8ntd?file=app/form-field-prefix-suffix-example.html
There are some errors and typos you should fix in your Stackblitz:您应该在 Stackblitz 中修复一些错误和拼写错误:
Remove brackets from [formControlName]
从
[formControlName]
中删除括号
Remove min
and max
attributes from <input>
as you've already specified them using validators
从
<input>
中删除min
和max
属性,因为您已经使用validators
指定了它们
Move <mat-error>
inside <mat-form-field>
将
<mat-error>
移到<mat-form-field>
For the error condition, you should use formGroupName.get('FormControlName').hasError('validatorName')
对于错误情况,您应该使用
formGroupName.get('FormControlName').hasError('validatorName')
Remove style="color: red"
from <mat-error>
, this is already the default style for the error message.从
<mat-error>
中删除style="color: red"
,这已经是错误消息的默认样式。
Fix the typo this.formBuilder.group
to be this.fb.group
将错别字
this.formBuilder.group
修正为this.fb.group
Here is Stackblitz after fixing the above errors.这是修复上述错误后的Stackblitz 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.