当验证器设置为minLength

时间:2018-05-07 12:47:18

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

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

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

问题是当字段为空时{{form.controls.idAnnuaire.valid }} 设置为true。 (期待虚假)

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

,则用户可以发送表单

Stackblitz demo

1 个答案:

答案 0 :(得分:1)

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



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