Paritosh
Paritosh

Reputation: 4503

angular input required field not working

I have a form used for creating a new entity as below:

<form #createAppForm="ngForm"
        (ngSubmit)="createApplication(createAppForm.value)"
        autocomplete="false" novalidate>
    <div class="form-group"
         [ngClass]="{'error': createAppForm.controls.applicationName?.invalid && createAppForm.controls.applicationName?.touched}">
    <label for="applicationName">Application Name</label>
    <em *ngIf="createAppForm.controls.applicationName?.invalid && createAppForm.controls.applicationName?.touched">Required</em>
    <input name="applicationName" required id="applicationName" type="text"
           class="form-control" placeholder="Name of application..." />
    </div>

I did not use ngModel in the input as the form is supposed to be blank when it comes up, and i'm submitting the createAppForm.value to the ngSubmit. However, whenever i check the form's valid property:

{{createAppForm.invalid}}

that is always returning false, even if i click in the input field and click out, without filling anything in. as a required field should it not return true?

I had used a similar form, editing data, in there i used [ngModel] and that works fine, validates the required field. Is [ngModel] needed here as well, and if so why? as i'm passing the form's values in.

Upvotes: 4

Views: 8962

Answers (2)

Uğur Din&#231;
Uğur Din&#231;

Reputation: 2455

You need to add ngModel to your input to be able to make use of Angular's form validation.

In a nutshell, ngForm only checks for elements that have an ngModel and a name. Without these, Angular won't validate.

Change it to this:

<input name="applicationName" ngModel required id="applicationName" type="text" class="form-control" placeholder="Name of application..." />

More info on the official docs.

Upvotes: 7

rojaswilmer
rojaswilmer

Reputation: 120

Did you create a formcontrol , in that form control you have to put all the validations.

Upvotes: 0

Related Questions