簡體   English   中英

HTML5最小最大驗證-Firefox

[英]HTML5 min max validation - firefox

我想使用HTML5最小最大驗證,但是此代碼:

<input id='quantity' name='quantity' type='number' min='0' max='5' />

在Firefox上不起作用。 所以我寫了js腳本,但這也行不通。 怎么了?

<input id='quantity' name='quantity' type='number' pattern='[1-9]*' oninput='check();'

<script language='javascript' type='text/javascript'>
function maxLength() {
    var quantity = document.getElementById('quantity');
    if (parseInt(quantity.value) > 5) {
        quantity.setCustomValidity('Alert');
    } else {
        quantity.setCustomValidity('');
    }
}
</script>

這是ff上的工作代碼

function maxLength() {
    var obj = document.getElementById('quantity');
    var max = obj.getAttribute('max');
    var min = obj.getAttribute('min');
    if (obj.value > max || obj.value < min) {
        obj.setCustomValidity('Alert ');
    } else {
        obj.setCustomValidity('');
    }
}

演示

您的代碼按原樣工作。

在此處輸入圖片說明

我想您忘了在<!doctype html>提到<!doctype html>了。

您必須在表單標簽中編寫HTML驗證

<form>
   <input id='quantity' name='quantity' type='number' min='0' max='5' />
</form>

您可以編寫一個onkeydownonkeypress事件,以檢查所按下的鍵。

document.getElementById("quantity").onkeypress = function(e){

   //for browser compatibility
   var keyCode = e.keyCode || e.charCode || e.which;
   if(keyCode<48||keyCode>53)
    {      
          //suppress the key or do whatever else you want with it
          return false;
    }

}

我沒有檢查過此代碼,因此請不要相信它,但這應該會有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM