Thursday, April 13, 2017

Angular 2 validations for input field

Angular places these classes automatically on the form. Same css classes are also available as properties for ng module

  • When the form is created all the fields are marked as ng-untouched
  • As we tab of the field the class changes to ng-touched
  • ng-pristine means that the field has not been touched
  • Once the user changes the inputs  ng-pristine changes to ng-dirty
  • ng-valid tells us that the field is valid
  • ng-invalid tells us that the filed in not valid
To use the properties on ng-model we need to reference ngmodel to a reference variable 

Change the input and the label color to red if it is touched
<div class="col-md-4 formGroup [class.has-error]=firstName.invalid && firstName.touched">
                   <label class="control-label">First Name :     
                 </label> 
                   <br/>
                   <!--$event passes the value !-->
                    <input #firstName="ngModel" type="text"  
                         required class="form-control" name="firstName" maxlength="3" 
                                     [ngModel]="userModel.firstName" 
                         /> <br/>
                    
                 </div>

Specifying regular expression for validations
<div class="col-md-4 formGroup [class.has-error]=firstName.invalid && firstName.touched">
                   <label class="control-label">First Name :     
                 </label> 
                   <br/>
                   <!--$event passes the value !-->
                    <input #firstName="ngModel" type="text" pattern="...+" 
                         required class="form-control" name="firstName" maxlength="3" 
                                     [ngModel]="userModel.firstName"
                      /> <br/>
                    
                 </div>

Validation for input field with conditional error message
<div class="col-md-12" id="addUsers">
                <div class="col-md-4 formGroup [class.has-error]=firstName.invalid && firstName.touched">
                   <label class="control-label">First Name :     
                 </label> 
                   <br/>
                   <!--$event passes the value !-->
                    <input #firstName="ngModel" type="text" pattern="...+" required class="form-control" 
                           name="firstName" maxlength="3" 
                           [ngModel]="userModel.firstName"  /> <br/>
                    
                 </div>
        </div>
         <div *ngIf="firstName.invalid && firstName.touched" class="row ">
           <div class="col-md-12">
                  <div class="alert alert-danger">
                   First Name is required and FirstName must be atleast 3 characters.
                 </div>
            </div>
        </div>

No comments:

Post a Comment