How to make type=“number” to positive numbers only

后端 未结 17 2290
既然无缘
既然无缘 2020-11-30 17:12

currently I have the following code


it comes out to something like this

相关标签:
17条回答
  • 2020-11-30 17:58

    You can use the following to make type="number" accept positive numbers only:

    input type="number" step="1" pattern="\d+"
    
    0 讨论(0)
  • 2020-11-30 17:58

    Try this:

    Yii2 : Validation rule 
    
        public function rules() {
        return [
    ['location_id', 'compare', 'compareValue' => 0', 'operator' => '>'],
            ];
    }
    
    0 讨论(0)
  • 2020-11-30 18:00

    Try

    <input type="number" pattern="^[0-9]" title='Only Number' min="1" step="1">

    0 讨论(0)
  • 2020-11-30 18:03

    add this code in your input type;

    onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57"
    

    for example:

    <input type="text" name="age" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" />
    
    0 讨论(0)
  • 2020-11-30 18:03

    Other solution is to use Js to make it positive (min option can be disabled and is not valid when the user types smth) The negative if is not necessary and on('keydown') event can also be used!

    let $numberInput =  $('#whatEverId');
    $numberInput.on('change', function(){
        let numberInputText = $numberInput.val();
        if(numberInputText.includes('-')){
            $numberInput.val(Math.abs($numberInput.val()));
        }
    });
    
    0 讨论(0)
  • 2020-11-30 18:07

    With text type of input you can use this for a better validation,

    return (event.keyCode? (event.keyCode == 69 ? false : event.keyCode >= 48 && event.keyCode <= 57) : (event.charCode >= 48 && event.charCode <= 57))? true : event.preventDefault();
    
    0 讨论(0)
提交回复
热议问题