Пустое поле управления действует, если для валидаторов установлено значение minLength - PullRequest
0 голосов
/ 07 мая 2018

Я создал форму с элементами управления.

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

проблема в том, что когда поле пусто, {{form.controls.idAnnuaire.valid }} устанавливается на true. (Ожидается ложь)

Я бы не стал устанавливать контрольную форму как обязательную, поскольку пользователь может отправить форму, если он заполнит другие поля ввода вместо idAnnuaire

Демонстрация Stackblitz

1 Ответ

0 голосов
/ 07 мая 2018

Есть несколько решений для этого - однако, я думаю, что лучший выбор для этого конкретного сценария - создать собственный валидатор. Это может выглядеть примерно так:

// 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
              ])
            )
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...