Home > Mobile >  How to restrict entering a colon in input text field, and auto populate it after entering 2 digits
How to restrict entering a colon in input text field, and auto populate it after entering 2 digits

Time:07-08

I am designing a time (HH:MM) field using input type text. How to restrict entering a colon manually in input field and auto populate it after 2nd digit? Though I am able to auto populate colon at 3rd place, how to restrict it adding manually at other places. `

const colReg = /([0-9]{2}(?!:))/g;
      if (event.target.value.length < 3) {
        event.target.value = event.target.value.replace(colReg, "$1:");
      }
      if (event.target.value.length === 5 && event.target.value.charAt(4) === ':') {
        event.target.value.replace(0);
     }

` enter image description here

CodePudding user response:

Here is the answer that should work smoothly.

<input data-val="true"
 data-val-regex="Invalid Time."
 data-val-regex-pattern="^(0[1-9]|1[0-2]):[0-5][0-9] (am|pm|AM|PM)$"
 name="StartTime" type="time" value="" />

I also noticed that people using those data attributes, still use type=" text". I assume that is the reason why it "returns the invalid time when using the chrome time picker".

I haven't find any case where type="time" works with other patterns (even with data-), and it seems this answer already explained it: html5 time inputs shows 12 hours

If you really need to have the AM and PM you can try to use type="text" with the regex pattern and trigger the datepicker through Javascript.

If you liked the answer and if it works, please do upvote it. Thank you.

CodePudding user response:

Here's an example of how I would have done it:

component.ts:

export class AppComponent {
  time = '';

  onType(event) {
    const regex = /^\d $/;
    return (
      (regex.test(event.key) || event.key === 'Backspace') &&
      this.time.length < 5
    );
  }

  updateColon() {
    if (this.time.length === 2) {
      this.time  = ':';
    }
  }
}

html:

<input [(ngModel)]="time" (keydown)="onType($event)" (ngModelChange)="updateColon()">
<div>{{ time }}</div>

Stackblitz demo

  • Related