Validation of time input in Angular7 using reactive forms with Material design

Dealing with an angular 7 reactive form, the input field in this form allows users to view and modify time. The issue arises when users enter nonsensical numbers in this field that do not align with valid time ranges (e.g., hours should be between 1-24, minutes between 1-60). My concern is how can I validate the user's input in the time field and only activate the Save button if it is valid?

Note: From my testing experience, even if users enter nonsensical time values, they are not saved in the database, possibly due to SQL rejecting such entries.

I have searched online but could not find a solution. Angular provides validators for email fields, but nothing specific for time validation within forms.

This is how I have defined my form:

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

And this is the corresponding HTML code:

<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 am looking for a way to validate any user input that does not make sense in terms of time, so that the Save button remains inactive unless a valid time value is entered.

Your help and guidance would be greatly appreciated.

Answer №1

If you're looking to incorporate time input in your HTML, you can utilize the type="time" attribute or consider using a library like JsDaddy/ngx-mask, which is available on Github. Here's how you can implement it:

When using MatInput in HTML:

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

Utilizing ngx-mas:

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

It's always beneficial to include type="time" for all input fields where time input is required.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

eslint rule prohibiting directly checking numbers

Does eslint have a rule that flags an error for the code snippet below: function parseNumber(numberToCheck: number | undefined) { // I want an error here: !0 is true, so we will get "no number" here if (!numberToCheck) { return "no n ...

Inform TypeScript about functions that are dynamically defined

I am implementing a unique class structure as shown below: class App<objectList extends {}> { private objects: Map<keyof objectList, any> = new Map(); add<T extends keyof objectList>(name: T, type: objectList[T]) { this.obj ...

Is it possible for a TypeScript interface to inherit from a Function?

While studying Angular, I found this intriguing declaration: interface IMessagesOperation extends Function { (messages: Message[]): Message[]; } I'm curious about what this means, especially why Function is capitalized as F instead of being lowercase ...

Angular 14: Creating a Dynamic Component with NgControl as a Dependency

I am currently trying to dynamically add a component to the DOM using ViewContainerRef's createComponent method. The challenge I am facing is that the component relies on NgControl, and my ultimate goal is to incorporate these components into a form u ...

What is causing this error to appear during the npm install process in my Angular project?

I encountered an issue in my Angular 7 project recently. When running npm install, the following error occurred: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-pro ...

Unexpected behavior with Angular 10 behavior subject - encountering null value after invoking .next(value) function

Can anyone help me solve the mystery of why my user value turns null after I log in? This is the login page where an API is called and the result is obtained as shown below: https://i.stack.imgur.com/kDjSy.png Here is the authentication service implemen ...

Utilizing TypeScript to spread properties onto a component and destructure them from within components

I'm trying to optimize my use of props spreading and destructuring when working with components. Currently, I spread my props in this manner: <RepositoryItem {...node} /> Then, within the component, I destructure the props like so: interface ...

Create an asynchronous observable named Input, then utilize it to conduct operations within a child component

Struggling a bit with the observable. I have data in my API that I am returning as an observable (using BehaviorSubject and exposing it as a get property) to pass asynchronously to my child component. If I bind the data directly to the UI using safe navi ...

MVC Razor View does not display line breaks

Generated in the controller is a string value that looks like this: cc.lstchat = "Reply the Number with your question... <br />"; foreach (clsChat item in lstchat) { cc.lstchat =cc.lstchat + ite ...

The field 'password' is not found in the data type 'User | undefined'

Howdy everyone, I've encountered an issue stating "Property '_doc' does not exist on type 'User & { _id: ObjectId; }'" in one of my controller documents while trying to fetch a particular user. My backend database is implemented us ...

Tips for managing the save file dialog box in Firefox with Selenium using C#

I am currently working with Selenium to test a website that includes the ability to download online videos. The website is built using ASP.NET. Whenever I click on the download button, a save file dialog pops up which Selenium is unable to handle. Is the ...

Maintaining TextBox State in ASP.Net Through Postbacks

Can anyone help me figure out how to maintain the control state that has been modified in Javascript? I am working with two TextBoxes, one DropDownList, and a button (all Runat=Server) in C# ASP.net 2010 Express. The first textbox accepts any user in ...

Unraveling NGRX: a guide to invoking factory selectors from within additional selectors

NGRX has deprecated selectors with props in version 11. The recommended method now is to create factory selectors. How can you nest selectors or call one from another and pass the state between them? Prior to the change, if we had the following two selec ...

Exploring different pages in Angular2 and Ionic2

I am encountering difficulties when it comes to navigating between pages in Angular2 / Ionic2. When attempting to navigate to a new page using the code below: import {Page, NavController} from 'ionic-angular'; import {HomePage} from '../ho ...

Implement the click event binding using classes in Angular 2

If I have the template below, how can I use TypeScript to bind a click event by class? My goal is to retrieve attributes of the clicked element. <ul> <li id="1" class="selectModal">First</li> <li id="2" class="selectModal">Seco ...

View Destruction Error: Trying to utilize a view that has been destroyed. Please identify changes

Currently dealing with an Angular application (Angular7) and encountered unexpected console errors. Struggling to pinpoint the exact cause of these errors. Seeking guidance on why they might be occurring. Check out this image for reference ...

Create a simulated class to serve as a property within a service

Currently, I'm working on an Ionic application and have created an AlertService class with two properties: messageAlert: Alert; errorAlert: Alert; The Alert class belongs to the Ionic framework, so I cannot modify it. To mock the Alert class, I came ...

Having trouble reaching a public method within an object passed to the @Input field of an Angular component

My configurator object declaration is as follows. export class Config { constructor(public index: number, public junk: string[] = []) { } public count() : number { return this.junk.length; } } After declaring it, I pass it into the input decorated fi ...

Unable to see text scrolling in the div container

I am trying to manipulate a div that contains some phrases: <div class="container"> <div class="phrase-doc">Lorem ipsum bla bla</div> <div class="phrase-doc">Lorem ipsum bla bla</div> <di ...

What is the process for swiftly incorporating newly generated rows into a different table?

There is a table called product with a primary key named id. I want to link this key to another table named pro_size_tbl in the following manner: pro_size_tbl ================== id productid sizeid When a user adds a product, the sizes of the products a ...