I have the following input number:
<input type="number" id="quantity" name="quantity" (change)="firstRangePointChanged($event)" >
I want to prevent the user from inputting invalid values like --99 (--) instead of (-) , I have tried to use:
if (Number.isNaN(num)) {
event.preventDefault();
but it isn't working.
I want to allow a negative numbers but not --99. I want that if the user inserts invalid number, then return the value to the previous one (the last valid value of that input):
firstRangePointChanged(event) {
const num = parseFloat(event.target.value);
if (Number.isNaN(num)) {
event.preventDefault();
return;
}
}
you can simply use regex in pattern to do that. for example:
<input type="text" id="country_code" name="country_code"
pattern="[A-Za-z]{3}" title="Three letter country code">
remember for use pattern, you must use type:"text" to allow you to use regex in pattern
function is_validNumber(n){ // check value is number or not if( n == NaN ){ return false; } let b = typeof n; if( b == 'number' || b == 'string' ){ // Math.round(Number(n):to supported decimal number return String(n).length? Number.isInteger( Number(n) ): false; } return false; } // ========================================================= function numValidation_(n){ // add history valid number of this input if( n.history_validNumber == undefined ){ n.history_validNumber = 0; // default value } let val_ = n.value; if( is_validNumber(val_) ){ n.history_validNumber = val_; // add history console.log('valid'); }else{ // invalid n.value = n.history_validNumber; console.log(`invalid, set last valid:${n.history_validNumber}`); } }
<input type="number" onchange="numValidation_(this)" />
You could handle this with regular expression like the example:
Angular version is:
let {pattern} = Validators;
this.formGroup = this.fb.group({
price:['',pattern("^([1-9]+[0-9]* | [1-9])$")]
})
Bind the form group to your input to only accept positive numbers, replacing your desired pattern.
In your template:
<form [ngForm]="formGroup">
<label for="price">Price</label>
<input type="number" name="price" formControlName="price" />
</form>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.