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.

1
  • You can create custom validator if there is no better solution. Commented Oct 27, 2022 at 13:44

3 Answers 3

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!

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.