2

I'm currently trying to validate a textarea in angular 2 to NOT have only whitespaces or line breaks (/n or /r)

I already tried this approach but I'm concern that when using it with a <textarea> any line break invalidate the input even if there's value in it, so when someone hits enter to create a new line the valid pattern transforms into an invalid one.

See this plunker for more information.

Basically:

<textarea autocomplete="off" [formControl]="newComment" id="comment"></textarea>

<button type="submit" [disabled]="!newComment.value || newComment.valid">
    Comment
</button>

and

newComment = new FormControl('', [Validators.pattern("\\s*")]);

So my point is that I get that to work but I'm sure I'm doing it wrong, because when I inspect the textarea the ng values show ng-invalid and I'm sure I'm mixing concepts.

To me, when it's invalid is when we should disable the input and not the other way around, but because Validators.pattern is about stuff that matches into that pattern it's like we have to use ! and invert the ouput of the ng-valid property. Am I right?

Thank you so much for your help.

EDIT: I know my logic matches when there're white spaces or line breaks, but it's because is the easiest way to discard "empty" textareas, but I'm looking for a clearer way to do this.

soni
  • 687
  • 1
  • 8
  • 23

1 Answers1

4

I had a similar problem a while ago, the only way to solve, was creating a custom function to validate the field, because Regex was invalidating text areas with other desirable chars like line-breaks:

export function validateEmptyField(c: FormControl) {
  return c.value && !c.value.trim() ? {
    required: {
      valid: false
    }
  } : null;
}

Usage:

newComment = new FormControl('', [validateEmptyField]);
Fals
  • 6,813
  • 4
  • 23
  • 43
  • Thanks Fals! This was actually my second choice, but I refused to admit there wasn't a simpler solution using validators pattern and regex. I'll apply what you suggested and mark your solution as the accepted answer. :) – soni Dec 19 '17 at 08:30