i have the following input number:
<input type="number" id="quantity" name="quantity" (change)="firstRangePointChanged($event)" >
I want to prevent from the user to insert invalid input like --99 (--) instead of (-) I have tried to use
if (Number.isNaN(num)) {
event.preventDefault();
but it is not working... I want to allow a negative numbers but not --99 I want that if the user insert 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;
}
}
CodePudding user response:
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)" />
CodePudding user response:
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