使用formBuilder显示模板中maxLength规则的字符数



我正在尝试验证我的文本字段的最大长度是否为'x'值。并且我希望这个消息从视图中动态显示。

this.register= this.formBuilder.group({
cellphone:[
null,
Validators.compose([Validators.required, Validators.maxLength(50)])
]
})

例如:

<div *ngIf="this.register.get("cellphone").hasError('maxlength')">
(maxlength is: {{}} digits);
</div>

我该怎么做?我需要知道规则的价值。如果我定义文本字段的最大长度为5,我希望在视图中动态地获得这个5。5可能会有所不同,所以我想动态地进行

本教程:例如,创建一个带有变量minlength的用户名验证字段的loginForm

组件

minlength = 5;
username = new FormControl('', [ Validators.required, Validators.minLength(this.minlength)]);
loginForm: FormGroup = this.builder.group({
username : this.username 
});

HTML

<form [formGroup]="loginForm" (ngSubmit)="login()">
<input  type="text" name="username" id="username" [formControl]="username">
<div [hidden]="username.valid || username.untouched">
<div>
The following problems have been found with the username:
</div>
<div [hidden]="!username.hasError('minlength')">
Username can not be shorter than {{ minlength }} characters.
</div>
<div [hidden]="!username.hasError('required')">
Username is required.
</div>
</div>
</form>

你可以启发它创建你的手机表单。

如果您有类似的

this.myform3=this.fb.group({
item:['',Validators.maxLength(10)]
})
<div *ngIf="myform3"  [formGroup]="myform3">
<input formControlName="item">
<div *ngIf="myform3.get('item').errors?.maxlength">
<pre>{{myform3.get('item').errors|json}}</pre>
</div> 
</div>

你可以在myform3.get('item'(.errors中看到?。maxlength.requiredLength具有所需的长度,并且在myform3.get('item'(.errors?中?。maxlength.actualLength可以写入的实际长度

<div *ngIf="myform3.get('item').errors?.maxlength">
the max length is {{myform3.get('item').errors?.maxlength.requiredLength}} 
and you write {{myform3.get('item').errors?.maxlength.actualLength}} characteres
</div> 

提示:如果无效,则所有验证器都返回一个对象。您可以检查返回对象,如您在示例中看到的那样。作为惯例,如果我们编写自己的自定义验证器,我们会让它返回一个有代表性的对象

最新更新