我想只得到正的值,有什么方法来防止它只使用html 请不要建议验证方法


当前回答

这个代码对我来说工作得很好。你能查一下吗:

<input type="number" name="test" min="0" oninput="validity.valid||(value='');">

其他回答

仅供参考:使用jQuery,你可以用以下代码覆盖focusout上的负值:

$(document).ready(function(){
    $("body").delegate('#myInputNumber', 'focusout', function(){
        if($(this).val() < 0){
            $(this).val('0');
        }
    });
});

这并不能取代服务器端验证!

下面是一个角度上的解决方案:

创建一个类OnlyNumber

import {Directive, ElementRef, HostListener} from '@angular/core';

@Directive({
  selector: '[OnlyNumber]'
})
export class OnlyNumber {

  // Allow decimal numbers. The \. is only allowed once to occur
  private regex: RegExp = new RegExp(/^[0-9]+(\.[0-9]*){0,1}$/g);

  // Allow key codes for special events. Reflect :
  // Backspace, tab, end, home
  private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home'];

  constructor(private el: ElementRef) {
  }

  @HostListener('keydown', ['$event'])
  onKeyDown(event: KeyboardEvent) {
    // Allow Backspace, tab, end, and home keys
    if (this.specialKeys.indexOf(event.key) !== -1) {
      return;
    }

    // Do not use event.keycode this is deprecated.
    // See: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
    let current: string = this.el.nativeElement.value;
    // We need this because the current value on the DOM element
    // is not yet updated with the value from this event
    let next: string = current.concat(event.key);
    if (next && !String(next).match(this.regex)) {
      event.preventDefault();
    }
  }
}

将OnlyNumber添加到app.module.ts中的声明中,并像这样在应用程序的任何地方使用它

<input OnlyNumber="true">

简单地使用min="0"

< v-text-field v模型=“abc” 类= " ml-1 rounded-0” 概述了 密集的 label = "数量" type = "数量" min = " 0 " > < / v-text-field >

< input type = "数量" name = " credit_days "模式= ^ \[-]+” # credit_days = " ngModel " class = "表单控件” 占位符="{{'输入信用天数' |翻译}}" min="0" [(ngModel)] = " provider.credit_days " onkeypress = "返回(事件。charCode == 8 ||事件。charCode == 0 || 事件。charCode == 13) ?Null:事件。charCode >= 48 &&事件。charCode < = 57" onpaste="return false"> .

oninput="this.value=(this.value   < Number(this.min) || this.value   > Number(this.max))  ? '' : this.value;"