validators的maxlength和minlength
时间: 2024-05-03 15:21:33 浏览: 12
validators中的maxlength和minlength分别用于验证输入的字符串的最大长度和最小长度。
maxlength用法示例:
```
import { FormControl, Validators } from '@angular/forms';
const control = new FormControl('', [
Validators.maxLength(10)
]);
console.log(control.errors); // null
control.setValue('Hello World!');
console.log(control.errors); // { maxlength: { requiredLength: 10, actualLength: 12 } }
```
在上述示例中,创建了一个FormControl,并使用Validators.maxLength(10)进行验证。当调用setValue()方法输入的字符串长度超过10时,控件会返回一个包含maxlength属性的错误对象。
minlength用法示例:
```
import { FormControl, Validators } from '@angular/forms';
const control = new FormControl('', [
Validators.minLength(5)
]);
console.log(control.errors); // null
control.setValue('Hello');
console.log(control.errors); // null
control.setValue('Hi');
console.log(control.errors); // { minlength: { requiredLength: 5, actualLength: 2 } }
```
在上述示例中,创建了一个FormControl,并使用Validators.minLength(5)进行验证。当调用setValue()方法输入的字符串长度小于5时,控件会返回一个包含minlength属性的错误对象。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)