Angular 2 form validation not working

efarley picture efarley · Aug 23, 2016 · Viewed 7.2k times · Source

I have an angular 2 application (RC.4) and I'm having issues with form validation.

I have the below form code in my template.

<div class='modal'>
    <form #modalForm='ngForm'>
      <div class='heading'>
        <h4>{{_title}}</h4>
        <div class='close-icon' (click)='close()'></div>
      </div>
      <div class='body'>
        <input type='text' name='projectName' [(ngModel)]='projectName' required placeholder='Give your project a name...' id='focusOnMe'>
      </div>
      <div class='controls'>
        <button class='btn btn-secondary' (click)='close()'>Cancel</button>
        <button type='submit' class='btn' (click)='sendAction()' [disabled]='!modalForm.form.valid'>{{_action}}</button>
      </div>
    </form>
  </div>

As you can see I name the form element and set it to ngForm and then on the input I include the required attribute and finally on the submit button I say [disabled]=!modalForm.form.valid however for some reason the form is always flagged as valid even when the required input is empty. What am I missing here?

Answer

Ben Richards picture Ben Richards · Aug 23, 2016

For Angular 2 RC 4:

You are missing the part where you tell the form that your "projectName" input should be part of the form validation. Just add "ngControl='inputId'":

<input type='text' 
       name='projectName' 
       ngControl="projectName" 
       [(ngModel)]='projectName' 
       required 
       placeholder='Give your project a name...' 
       id='focusOnMe'>

For Angular 2.0 Final:

  1. Add [formGrooup] to your form:

<form [formGroup]="modalForm">

  1. Add "formControlName" to your control:

    <input type='text' name='projectName' formControlName="projectName" [(ngModel)]='projectName' required placeholder='Give your project a name...' id='focusOnMe'>