Roberto
Roberto

Reputation: 325

Angular validation message for required input after touched

I am using Angular reactive forms and I found here validation idea. It's pretty great but there is one problem. When the form is empty and I click on input, then it is going to get invalid class (red color) but no error message is display. Only after I put some text and delete it, the message will arrive. I am wondering how can I change this 'if steatment' to work as it shoud

if (control && control.dirty && !control.valid) 

I just want to add error message which will occur after I click on input and then leave it (still) empty. Do You have any idea how to achive it?

Upvotes: 1

Views: 11018

Answers (2)

Vega
Vega

Reputation: 28708

If you set name control to following:

...name: ["", [Validators.required],....

then should be able to do the following:

<span class="error" *ngIf="(user.get('username').touched && !user.get('username').value) ||  user.get('username').invalid">Error on username</span>

or, if you mind about the layout change (as *ngIf will remove it from the DOM), you can apply [hidden] property with the reverse logic:

<span class="error" [hidden]="!user.get('username').touched || user.get('username').value || user.get('username').invalid">

Plunker

Upvotes: 4

diopside
diopside

Reputation: 3062

Its tough to answer without a working example, but in general, I use the opposite logic to what you're doing. Basically, specify the conditions when you wouldn't show the error, and always show it otherwise. For me that's usually

 (!password.touched || (password.touched && password.valid))

For example. Also, don't forget about 'pristine'.

Upvotes: 0

Related Questions