I have an input text field. <input type="text" [ngModel]="textvalue | currencyinrhello" (ngModelChange)="onTextChange($event)" (keypress)="restrictNumeric($event)" />
i want to restrict the value of the input from 15,000 to 5,00,000. I don't want the user to input a number above it.
-
any reason for using keypress event?– MMKCommented Dec 30, 2016 at 14:19
3 Answers
You can use HTML5 native. You don't need any angular 2 code here. Only for form validation. If user types in some number which is not inside the range, or any invalid character, the form will be invalid.
<input type="number" name="quantity" min="15000" max="5000000">
In angular2 way, you can use directives.
@Directive({
selector: '[restrict]',
})
export class InputRestricter{
@Input('restrict_minvalue') minValue: number;
constructor(private el: ElementRef,private renderer: Renderer) {
}
@HostListener('keyup',['$event']) onKeyUp(event){
if(this.minValue){
let el = <HTMLSelectElement> event.target;
if ($(el).val() <= this.minValue) {
el.setCustomValidity('Value is invalid');
} else {
el.setCustomValidity('');
}
}
}
and then use the directive in your template
<input restrict [restrict_minvalue]="15000"/>
The directive will make your input invalid, if the input value is less than 15000. You can implement max value ability in same way.
-
I want the data to automatically change to 500000 even if you try to put a number above it, on runtime. sorry for not completing the question. Commented Dec 30, 2016 at 12:36
-
@VishalNair Then you can simply set the value $(el).val("15000") instead of setting it invalid. In the directive you have the input element, you can manage it however you want. Commented Dec 30, 2016 at 14:16
try something like this, i have used keyup event
import {Component, Input} from 'angular2/core';
@Component({
selector: 'app',
template: `
<label>Enter the Amount:</label>
<input type="text" #textbox [(ngModel)]="textvalue" (keyup)="restrictNumeric($event, textbox.value, 15000, 500000)" />
`
})
export class App {
string: textvalue;
restrictNumeric(event, value, min, max)
{
if(parseInt(value) < min || isNaN(parseInt(value)))
console.log("invalid min value");
else if(parseInt(value) > max || isNaN(parseInt(value))
this.textvalue = 500000;
}
}