Is it possible to get minlength value from formcontrol?

走远了吗. 提交于 2021-02-19 01:33:29

问题


So i have my form validation. And my question is can i get for example a minlength value which i passed at creating formControl?

I havent found any information.

This is my dumb component and i want to get minlength value to pass to information. Now i need to pass it via @Input().

title: ['', [Validators.required, Validators.minLength(4), Validators.maxLength(20)]]

.

<div class="validation-window">
  <p *ngIf="errors.required">
    {{field}} required
  </p>
  <p *ngIf="formControl.hasError('minlength')">
      {{field}} at least {{minLegth}} characters
  </p>
  <p *ngIf="formControl.hasError('maxlength')">
      {{field}} at least {{maxLength}} characters
  </p>
</div>

I want to replace {{maxLength}} with something like formControl.validators.minlength.value;


回答1:


Yes, you can access the number of the length, both in maxlength and minlength. You can find it inside the error object, where it lies under .maxlength.requiredLength && minlength.requiredLength. There is also a field with actualLength, but you don't seem to need it, but if you sometimes do! :)

<p *ngIf="formControl.hasError('maxlength')">
  {{field}} at max {{formControl.errors.maxlength.requiredLength}} characters
</p>

<p *ngIf="formControl.hasError('minlength')">
  {{field}} at least {{formControl.errors.minlength.requiredLength}} characters
</p>

DEMO




回答2:


I am afraid that there is no such thing in angular, for example on angular.io, in the build-in validators example, they are using a raw coded value for the minlength error Built-in validators

<div *ngIf="name.errors.minlength">
    Name must be at least 4 characters long.
</div>

But you can store the minLength/maxLength value in a variable and display that variable instead.



来源:https://stackoverflow.com/questions/55975103/is-it-possible-to-get-minlength-value-from-formcontrol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!