簡體   English   中英

<input type=“text” maxlength=“4”>不應以逗號和點數來表示最大長度

[英]<input type=“text” maxlength=“4”> should not count comma and dot in maxlength

我有一個輸入字段,其中包含數字和特殊字符,例如逗號和點,同時計算要跳過特殊字符的字段的maxLength。

我不想限制特殊字符。

預期輸出應為:-1,234(總長度:-4)

 <form action="/action_page.php"> Username: <input type="text" maxlength="3" id="myId"/> <input type="submit" value="Submit"> </form> 

jsfiddle鏈接在這里

嘗試添加以下javascript:

 window.onload = function() {

    var textInput = document.getElementById("myId");

    textInput.oninput = function() {
      var temp;
      temp = this.value.replace(/[^\w\s]/gi,'');
      if (temp.length > 3) {
        alert("Invalid"); // Or other stuff you want to do
      }
    };
  };

請注意,此代碼會實時檢查輸入

這應該使用javascript完成:

var input = document.getElementById('myId');

input.addEventListener('keyup', function () {
  // Checking length of string ignoring all non-digit and non-letter characters
  if (this.value.replace(/[^\d|[^a-zA-Z]]*/g, '').length == 3) { 
    console.log('stop and do whatever you need')
  }
})

您可以嘗試使用HTML5 pattern屬性。 只是代替maxlength類型的pattern並給它一些正則表達式。 可以做這樣的事情:

<form action="/action_page.php">
       Username: <input type="text" pattern="(?(?=^.\d{1,3},\d{1,3}$)^.{5}$|^.{4}$)" id="myId"/>
    <input type="submit" value="Submit">
 </form>

暫無
暫無

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

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