简体   繁体   English

HTML 输入类型号,防止插入无效号

[英]HTML input type number, prevent insert invalid number

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:我想防止用户输入无效值,例如 --99 (--) 而不是 (-) ,我尝试使用:

if (Number.isNaN(num)) {
          event.preventDefault();

but it isn't working.但它不起作用。

I want to allow a negative numbers but not --99.我想允许负数但不允许 --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: Angular 版本是:

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM