How to check number ranges in HTML input? (Angular 2)

In my Angular 2 application, I have a component with an input field that should accept a range of numbers.

More specifically, 2 cases:

  • range 0 [0] -23 (hours)
  • range O [0] -59 (minutes)

I use

<form> <input type="text" pattern="[0-9]"> <!-- 0-9 --> <input type="text" pattern="\d|1\d|2[0-3]"> <!-- 0-23 --> <input type="text" pattern="\d\d"> <!-- [0-99] --> </form> 

The problem is that I can basically type in anything ( as if the check were ignored ), including the text. I don't think this is an Angular 2 related issue as standard validation works like

  <input type="number"> 

allows you to enter only numbers (but any number that is not what I want)

I also tried with min = 0 and max = 23 (or 59) attributes with type number , but this does not work either.

+5
source share
2 answers
 <form> <input type="number" min="0" max="9"> <!-- 0-9 --> <input type="number" min="0" max="23"> <!-- 0-23 --> <input type="number" min="0" max="99"> <!-- [0-99] --> </form> 
+4
source

In the future, I decided using Angular 2 FormBuilder , as in:

c

  ... constructor(... private formBuilder: FormBuilder); timeForm: ControlGroup; ngOnInit(){ let regexPatterns = { // this can be improved hours: "[0-2]?[0-9]?", minutes: "[0-5]?[0-9]?" }; this.timeForm = this.formBuilder.group({ hour: ['', Validators.pattern(regexPatterns.hours)], minute: ['', Validators.pattern(regexPatterns.minutes)] }); 

HTML

  <form [ngFormModel]="timeForm"> <!-- additional validation (HTML 5) for 'required' --> <input type="text" required ngControl="hour"> <input type="text" required ngControl="minute"> </form> 
+3
source

All Articles