Elavarasan M
Elavarasan M

Reputation: 192

Validation message always displayed in Angular5 even the textbox have some values

I am using Angular5, new to Angular.

I have one textbox, added the validation to that field. It is working fine when the textbox is empty. But after entering some values in textbox, the validation message still displayed. Kindly help if anything wrong.

<form class="emp-form">  
  <div class="form-group">
    <label for="firstName">First Name</label>
      <input required ngModel name="firstName" id="firstName" class="form-control"  placeholder="First Name" #firstName="ngModel"/>
      <div class="alert alert-danger" *ngIf="!firstName.Valid">First Name is required</div>
    </div>
    </form>

Here First Name is required always displayed even entered some into textbox.

Thanks in Advance.

Upvotes: 0

Views: 330

Answers (2)

Arash
Arash

Reputation: 1826

Whatever Fateme mentioned is called Reactive Form but you are trying to validate simple form.

You'r code problem is that firstName.Valid should be firstName.valid

valid should be in camel case.

Upvotes: 2

Lia
Lia

Reputation: 11982

you can try something like:

<form [formGroup]="myForm" class="m-form m-form--fit m-form--label-align-right">
                <div class="form-group m-form__group row" [ngClass]="{
                    'has-danger': myForm.controls['firstName'].invalid && myForm.controls['firstName'].touched,
                    'has-success': myForm.controls['firstName'].valid && myForm.controls['firstName'].touched,
                    'has-no-action': myForm.controls['firstName'].untouched
                }">
                    <label class="col-form-label col-lg-3 col-sm-12" for="name-field">
                        First Name
                        <span class="required" aria-required="true"> * </span>
                    </label>
                    <div class="col-lg-4 col-md-9 col-sm-12">
                        <input type="text" class="form-control m-input" formControlName="firstName" name="firstName" id="name-field" placeholder="First Name">
                        <div class="form-control-feedback">Required Field May Not Be Empty</div>
                        <span class="m-form__help">Enter The User First Name</span>
                    </div>
               </div>
<form>

and in component:

this.myForm = this.formBuilder.group({
            "firstName": ['', Validators.required]
    });

Upvotes: 2

Related Questions