angular - 当验证器设置为 minLength 时,空字段控制有效
问题描述
我创建了一个带有 controlforms 的表单。
idAnnuaire: new FormControl('',[Validators.minLength(6),Validators.maxLength(6)]),
问题是当字段为空时{{form.controls.idAnnuaire.valid }}
设置为true
. (期待假)
我不会将 controlform 设置为 required 因为用户可以发送表单如果他填写其他输入而不是idAnnuaire
解决方案
有几个解决方案 - 但是,我认为这种特定场景的最佳选择是创建自定义验证器。它可能看起来像这样:
// Custom Validator file
// Uncomment this for the actual app - commented out for the snippet
// import { FormControl } from '@angular/forms';
// This should be removed - the acutal value should come from the form
const inputValidValue = { value: '123123' };
const inputInvalidValueLow = { value: '123' };
const inputInvalidValueHigh = { value: '123123123123' };
const inputInvalidValueNoValue = { value: '' };
// this needs to be an exported function - snippet wont run if 'export' is there
function validateOptionalFieldWithLength(input){
return validateField(input, { validField: true });
}
// Uncomment this for the actual app - commented out for the snippet
// function validateField(input: FormControl, error: { [errorKey: string]: boolean }) {
function validateField(input, error) {
let isValidField = true;
let fieldValue = input.value;
if (fieldValue && fieldValue.length === 6 ) {
return null;
}
return error;
}
console.log('should be valid (null) : ' + validateOptionalFieldWithLength(inputValidValue));
console.log('should be invalid (error) : ' + validateOptionalFieldWithLength(inputInvalidValueLow));
console.log('should be invalid (error) : ' + validateOptionalFieldWithLength(inputInvalidValueHigh));
console.log('should be invalid (error) : ' + validateOptionalFieldWithLength(inputInvalidValueNoValue));
// You component
// Import your custom validator
idAnnuaire: new FormControl('',
Validators.compose([
validateOptionalFieldWithLength
])
)
推荐阅读
- c# - 您将如何使用 LINQ 编写此映射过滤器链?
- angular - 带有Angular 9基本安装的CKEditor5导致“'ckeditor'不是已知元素:'”
- wordpress - Woocommerce 根据付款方式更改总价
- javascript - 理解 Vue 和 Return 和 Async Await
- r - 结合renderUI、dataTableOutput、renderDataTable和reactive
- azure - 如何合并存储在 Azure Blob 中的两个视频?
- node.js - 如何专门为 SpotifyAPI 进行 API GET 调用,getUserPlaylists()?
- vb.net - 我想通过按 f5 键来显示一个表单,但它在 vb.net 中不起作用
- python - 可以防止调用“__del__()”的“参考循环”示例?
- apache-spark - 网络超时在 kubernetes 中初始化 spark 上下文(独立驱动程序)