angular - 当验证器设置为 minLength 时空字段控制有效

标签 angular typescript angular-reactive-forms angular-forms

我创建了一个带有控件表单的表单。

idAnnuaire: new FormControl('',[Validators.minLength(6),Validators.maxLength(6)]),

问题是当字段为空时{{form.controls.idAnnuaire.valid }} 设置为 true。 (预计错误)

我不会将 controlform 设置为必需,因为如果用户填写其他输入而不是 idAnnuaire

,则可以发送表单

Stackblitz demo

最佳答案

对此有几种解决方案 - 但是,我认为针对此特定场景的最佳选择是创建自定义验证器。它可能看起来像这样:

// 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
              ])
            )

关于angular - 当验证器设置为 minLength 时空字段控制有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50214622/

相关文章:

angular - Agular2 + typescript + 文件上传

reactjs - <Question> 组件显示类型保护失败的不同类型的问题

typescript - 如何理解 TypeScript 接口(interface)中的语法 [key : string]

javascript - 如何使用 Angular 8 在互联网重新连接时重新发送失败的 API 请求?

angular - ionic 2 : How to make a sliding menu from the bottom

Angular Form 控件在组件初始化时无效,没有任何操作

html - 如何创建嵌套的动态表单元素

Angular 异步验证器的状态未反射(reflect)在表单字段的错误状态中

javascript - 在 Typescript 中使用 map

Angular 2无法使模型对象的json常量