Search code examples
angularvalidationangular-reactive-forms

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?


Solution

  • 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