Angular2 <form> input validation

595 Views Asked by At

I have an input field which is mandatory in order to proceed to the next page can't figure out how to validate the input(Name) ...searched online and tried various things but to no avail...

Any help highly appreciated...

<form>
  <div>
      <div class="form-group" style="width:50%">
        <label class="label label-info" for="Name">Enter Name:</label>
        <input [(ngModel)]="Name" class="form-control" required type="text" 
        name="Name" id="Name" />
  </div>
  <button kendoButton  id="btnSearch" [primary]="true" 
          (click)="redirect()">Next</button>
</div>
</form>
2

There are 2 best solutions below

0
On BEST ANSWER

Pretty simple. I recommend making a model-driven form.

In your component:

myForm: FormGroup;

constructor(private fb: FormBuilder) {
      // We inject FormBuilder to our component

      // Now, we instantiate myForm with FormBuilder
       this.myForm = this.fb.group({
                name: [null, Validators.required]
            });

  }

In the template, we will replace [(ngModel)] with formControlName="name".

For your Next button we will disable it when form is not valid: [disabled]='!myForm.valid'.

Also notice [formGroup]='myForm' part.

<form [formGroup]='myForm'>
  <div>
      <div class="form-group" style="width:50%">
        <label class="label label-info" for="Name">Enter Name:</label>
        <input formControlName="name" class="form-control" required type="text" 
        name="Name" id="Name" />
  </div>
  <button kendoButton [disabled]='!myForm.valid' id="btnSearch" [primary]="true" 
          (click)="redirect()">Next</button>
</div>
</form>
0
On

If you need to use Template Driven Forms rather than Reactive Forms, you can use a template reference variable in combination with reference to ngModel to watch for errors on the Name input field and do something like disable the button until valid:

<form>
  <div>
      <div class="form-group" style="width:50%">
        <label class="label label-info" for="Name">Enter Name:</label>
        <input [(ngModel)]="Name" class="form-control" required type="text" 
        name="Name" id="Name" #foo="ngModel" />
      </div>
  <button kendoButton  id="btnSearch" [primary]="true [disabled]="foo.errors" (click)="redirect()">Next</button>
  </div>
</form>

For larger forms however, validation in this way can quickly get messy having a template reference variable for each field. It might be worth considering Reactive Forms if validation and logic become more complex.

Here is a plunker demonstrating the functionality.