简体   繁体   中英

Angular7 reactive form material time input validation

I have an angular 7 reactive form, input field in this form is to let user see and modify time and then using Save() save it back to our db, the problem is that user can enter any none sense numbers in this field which dose not make sense in terms of Time.(like hours should be 1-24, Minutes 1-60) My question is how can I validate what user entered into time field and if its valid then let Save btn be active?

Note: Based on my testing even though its none sense time entry but while trying to save its not saving to db and its probably sql not letting that happen.

I googled but i could not find anything, also angular has only email Validators which u can put while defining form.

this is my form defination

timeForm: FormGroup = new FormGroup({
    Id: new FormControl(''),
    Time: new FormControl(''),
  });

and this is my HTML side

<form style="background-color: aliceblue;" [formGroup]="service.timeForm">
  <mat-grid-list cols="1" rowHeight="120px">
    <mat-grid-tile>
      <div class="form-controles-container">
        <input type="hidden" formControlName="Id" />
        <mat-form-field>
          <input formControlName="Time" matInput placeholder="Time" />
        </mat-form-field>
        <div class="button-row">
          <button mat-raised-button color="primary" type="submit" (click)="Save()">Save</button>
          <button mat-raised-button color="warn" (click)="Cancel()">Cancel</button>
        </div>
      </div>
    </mat-grid-tile>
  </mat-grid-list>
</form>

I need some sort of validation when user punch in any input which dose not make sense in Time my Save btn should not be activated.

I appreciate your help and guideline.

You can use the HTML type="time" or if you want more you can simply use a library like: JsDaddy/ngx-mask found on Github. Use it like this:

HTML with MatInput:

<input formControlName="Time" matInput placeholder="Time" type="time" />

With ngx-mas :

<input formControlName="Time" matInput placeholder="Time" mask="Hh:m0" />

Adding type="time" in all input time type use cases always help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM