0

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.

Juliano
  • 141
  • 1
  • 11

3 Answers3

1

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!

Juliano
  • 141
  • 1
  • 11
1

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;
  };
}
Chund
  • 355
  • 2
  • 15
  • That was my initial thought but I think in this case is unnecessary, Validator pattern a build in function so why re-invented the wheel? What is unreadable about regex ? – Juliano Oct 27 '22 at 15:39
0

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);
    };
  }
}
MoxxiManagarm
  • 8,735
  • 3
  • 14
  • 43