infodev
infodev

Reputation: 5235

Empty field control is valid when validators are set to minLength

I have created a form with a controlforms.

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

the problem is that when the field is empty {{form.controls.idAnnuaire.valid }} is set to true. ( Expecting false )

I would not set the controlform to required because user can send form if he fill the other inputs instead of idAnnuaire

Stackblitz demo

Upvotes: 3

Views: 4416

Answers (1)

Tucker
Tucker

Reputation: 1922

There are a couple of solutions to this - however, I think the best choice for this specific scenario is to create a custom validator. It could look something like this:

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

Upvotes: 2

Related Questions