Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FormBuilder validation is not working properly

I have this form that implements FormBuilder.

I need to show my custom validation message under the input field. With my code below, the validator can make a red "wrong" text appear whenever the input field is blank but it doesn't show my custom validation.

Please see code below for .html and .ts

<form [formGroup]="subscriptionForm">
      <h3 style="color: gray; text-align: center;">Registration</h3>
      <div class="row">
        <div class="col-md-6">
          <div class="md-form">
            <i class="fa fa-user prefix grey-text"></i>
            <input type="text" formControlName="UserName" name='UserName' id="UserName" class="form-control" mdbInputDirective>
            <label for="UserName">Your UserName</label>
            <div *ngIf="UserName?.invalid && (UserName?.dirty || UserName?.touched)" class="alert alert-danger">
              <div *ngIf="UserName?.errors.required">
                Username is required.
              </div>
            </div>
          </div>
        </div>
      </div>
</form>

constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.subscriptionForm = this.fb.group({
      UserName: [null, Validators.required],
    });
}

I have gone through the Angular - Form validation docs, that's where I got my codes, but I can't get it right. Thank you.

like image 306
stack questions Avatar asked Feb 24 '26 12:02

stack questions


1 Answers

Try to change

*ngIf="UserName?.invalid && (UserName?.dirty || UserName?.touched)"

To

*ngIf="subscriptionForm.get('UserName').hasError('required') && subscriptionForm.get('UserName').touched"

In the view:

<div *ngIf="subscriptionForm.get('UserName').hasError('required') && subscriptionForm.get('UserName').touched" class="alert alert-danger">
    Username is required.
</div>

Please try this Demo:

https://stackblitz.com/edit/angular-5xtbxm?file=app/app.component.html

like image 98
HDJEMAI Avatar answered Feb 27 '26 02:02

HDJEMAI