Juliano
Juliano

Reputation: 137

Angular 10 reactive form Validators minLength to ignore spaces

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.

Upvotes: 0

Views: 631

Answers (3)

MoxxiManagarm
MoxxiManagarm

Reputation: 9124

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);
    };
  }
}

Upvotes: 0

Chund
Chund

Reputation: 459

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;
  };
}

Upvotes: 1

Juliano
Juliano

Reputation: 137

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!

Upvotes: 1

Related Questions