Home > database >  Angular 10 reactive form Validators minLength to ignore spaces
Angular 10 reactive form Validators minLength to ignore spaces

Time:10-28

Is there any solution to use Validators.minLength(6) but to ignore spaces ?

E.G: 1234 5 this would validate but it shouldn't as I'm looking to validate 6 digits without spaces E.G: 1234 56

Thanks.

CodePudding user response:

As I've searched for Angular specific I couldn't find any answers, after searching more generic html minlength validation digits without spaces I've found something that pointed me to a solution. ref:html input pattern

It's the html input pattern attribute which we can also use in angular so my solution is:

Validators.pattern('\\s*(\\S\\s*){16,}')

The above worked really nice for me!

CodePudding user response:

While your pattern approach works, it is hardly considerable as "readable". In this case I would recommend you to look into Custom Validators.

Something like the following should be what you are looking for.

export function maxPrunedLength(length: number): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    const prunedValueLength = control.value.replaceAll(' ','').length;
    return prunedValueLength > length 
      ? {forbiddenName: {value: control.value}} 
      : null;
  };
}

CodePudding user response:

There is not. Validators.minLength(6) is a factory, that creates a function, which takes a FormControl and returns an error object or null - also called ValidatorFn. You can make use of it, by altering the provided control.

export class CustomValidators {
  static minLengthIgnoreWhitespace(length: number): ValidatorFn {
    return (control: AbstractControl) => {
      const modifiedControl: FormControl = new FormControl(control.value.replace(/\s/g, ''));
      return Validators.minLength(length)(modifiedControl);
    };
  }
}
  • Related