0

I'm using Angular and Angular Material. When validating input length using the minlength validator, empty input slips through. Is there a built-in support to validate "empty or shorter than"?

I could use required in combination with minlength, however, Angular Material styles such input and that's not desirable.

Should I implement custom validator?

5
  • please share your code, so someone can help. Commented Jul 17, 2017 at 23:05
  • So you are trying not to use validator required? Commented Jul 17, 2017 at 23:24
  • @Nehal precisely, as the field gets styled (thanks to the Angular Material) and that's something I'm trying to avoid Commented Jul 17, 2017 at 23:28
  • I am not sure what you mean by "field gets styled"!! Can you explain little bit more? Commented Jul 18, 2017 at 1:57
  • Sorry for the confusion nethan. Basically the design library appends asterisk to the field name Commented Jul 18, 2017 at 8:04

1 Answer 1

1

I could use required in combination with minlength, however, Angular Material styles such input and that's not desirable.

You could simply override their styling and it wouldn't be an issue.

Or you could, like you said, create a custom validator. But this should be used with FormBuilder which I'm not sure that you are using.

Here's one you could use, when given a better name of course:

export const MyCustomValidator = (length: number): ValidatorFn => {

  return (control: AbstractControl): {[key: string]: any} => {

    return ((!value ||) (value < length)) ? null : {
      myCustom: true
    };
  };
};
Sign up to request clarification or add additional context in comments.

1 Comment

Yea, I'm not using FormBuilder, however, your mention of styles made me take another look and apparently Angular Material added hideRequiredMarker recently and that solves the problem

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.