In my Angular 2 application I have a component with a input field which is supposed to accept a range of numbers.
More specifically, 2 cases:
I am using
<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 issue is that I can basically input anything (as if validation was ignored), including text. I don't think it's an issue related to Angular 2 since standard validation works, e.g.
<input type="number">
allows to input only numbers (but any number which is not what I want)
I also tried with min=0 and max=23 (or 59) attributes with type number but that doesn't work either.
The <input type="range"> defines a control for entering a number whose exact value is not important (like a slider control). Default range is 0 to 100. However, you can set restrictions on what numbers are accepted with the attributes below. Tip: Always add the <label> tag for best accessibility practices!
The simplest HTML5 validation feature is the required attribute. To make an input mandatory, add this attribute to the element. When this attribute is set, the element matches the :required UI pseudo-class and the form won't submit, displaying an error message on submission when the input is empty.
Approach: We have used isNaN() function for validation of the textfield for numeric value only. Text-field data is passed in the function and if passed data is number then isNan() returns true and if data is not number or combination of both number and alphabets then it returns false.
Validation should aim to be as accommodating as possible of different forms of input for particular data types. For example, telephone numbers are written with different separators and digit groupings. Your form will be easier to use if it can interpret multiple notations. Also, it is helpful to be liberal with input.
<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>
For future reference, I solved by using Angular 2's FormBuilder as in:
ts
...
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With