0

I am just trying to show a cross mark when the username is blank or is not with required pattern and show a tick if input entered is valid.Bootstrap is-active and is-inactive class help it. Below is the code i tried with. I only get username is undefined. I seem to have gone wrong with implementation. Could you please help rectify?

<form  [formGroup]="profileForm" (ngSubmit)="onSubmit()">

                <input
                  type="text"
                  placeholder="Username / Email"
                  class="form-control"
                  formControlName="username"
                  [ngClass]="username.errors?'is-invalid':'is-valid'"
                  name="username"
                  id="username"
                />
    </form>

In ts

 profileForm = new FormGroup({
    username: new FormControl('',[Validators.required,Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$")])
  });

3 Answers 3

1

in .ts add

get userName() {
 return this.profileForm.get('userName');
}

in html add

[ngClass]="userName.hasError('pattern')" ? "is-invalid": "is-valid"

if you wish not to add any code in .ts file use

[ngClass]="profileForm.controls['userName'].hasError('pattern')" ? "is-invalid": "is-valid"
Sign up to request clarification or add additional context in comments.

Comments

0

There is indeed no username property in your component. So yes, username is undefined.

The only property we know about is named profileForm. You can get its control named username using profileForm.get('username'), and you can test if this control is valid using profileForm.get('username').valid.

Comments

0

Add the following snippet to your style sheet:

.ng-touched.ng-invalid:not(form) {
  @extend .is-invalid;
}

.ng-touched.ng-valid:not(form) {
  @extend .is-valid;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.