2

入力に設定するデータを検証しようとしています。de Validation HTML5を使用したい。

たとえば、「aaaa」が数値入力の有効なデータであるかどうかを確認したいとします。使用したかったのwillValidateですvalidityが、無効な値を設定できません。コンソールに次のように表示されます (Chrome):

指定された値「aaaa」は有効な数値ではありません。値は次の正規表現と一致する必要があります: -?(\d+|\d+.\d+|.\d+)([eE][-+]?\d+)?

エラーをキャッチしようとしましたが、それは Exception ではありません。入力値を取得しましたが、エラーの後は空です。

var value = "aaaa";

try {
    document.getElementById("input").value = value; // Shows a warn
} catch(err) {
    console.log(err.message); // Nothing catching
}

console.log( document.getElementById("input").value ); // It is empty

デモを参照してください。

より説明:

設定する値が入力型で有効かどうかを確認したい。入力に無効な値を設定し、willValidate または有効性を確認すると思いましたが、ブラウザに警告が表示され、入力値が空です。問題は、私のフロントエンドが JavaScript を介して入力値を設定するが、ユーザーが値を渡すことです。エラーが発生した場合、ユーザーにエラーを表示する必要があります。

更新:

警告が例外ではないことを知っています。任意の型で無効な入力値を設定するとエラーが表示されることを知りたいです。

4

4 に答える 4

1
var value = "aaaa";
document.getElementById("input").value = value;
if (document.getElementById("input").value == null || document.getElementById("input").value == "") {
        alert("Invalid value");
}
于 2016-05-23T07:07:47.720 に答える
0

それはエラーではなく、単なる警告だからです。コンソールで確認できます。

編集:質問で自分で言及しました)

できることはisNaN(value)、エラー オブジェクトをチェックしてスローすることです。

try {
 if(isNaN(value)) 
    throw new Error("not a number");
 else
    document.getElementById("input").value = value;
} catch(err) {
    document.getElementById("error").innerText = err.message;
}

例としてのjsFiddle

于 2016-05-20T11:48:07.307 に答える
0

.valueで設定されていることを確認するには、に表示されている警告に設定し、に 表示されているものと一致しない場合に行うjavascriptことができます。throwError.messageconsolecatchinput .valueRegExpconsole

ユーザー入力を確認するために、yupu はonkeydown, onpasteevents;を使用できます。要素を使用<label>して にメッセージを表示しhtmlonfocusイベントがlabel .innerHTML空の文字列の場合input .valueは空の文字列に設定します。

に表示されるメッセージは要素のプロパティconsoleにも設定されていることに注意してください。ただし、ユーザー入力では更新されず、 at に続く空の文字列に設定されます。inputcomputedNamealert()catch

<!DOCTYPE html>
<html>
<head>
  <script>
    window.onload = function() {
      
      var input = document.getElementById("input");
      var label = document.querySelector("[for=input]");

      function handleInvalid(el, val, e) {
        console.log("value:", val, "computedName:", el.comptedName);
        var message = "The specified value <mark>" + val 
                      + "</mark> is not a valid number. "
                      + "The value must match to "
                      + "the following regular expression: "
                      + "<code style=background:#eee;padding:2px>"                          
                      + "-?(\d+|\d+\.\d+|\.\d+)([eE][-+]?\d+)?</code>";
        // if `e` : `event` is not defined,
        // that is `val` : `"aaaa"` set at `try`;
        // not user input
        if (!e) {
          el.value = val;
          
        };

        if (!/-?(\d+|\d+\.\d+|\.\d+)([eE][-+]?\d+)?/.test(val)) {
          if (!e) {
            // `throw` `Error` to `catch`
            throw new Error(message);
          } else {
            label.innerHTML = message;
          }
        } else {
          // if `val` is matches `RegExp`, 
          // set `label` `.innerHTML` to empty string            
          label.innerHTML = ""
        }
      }

      function handleInput(e) { 
        label.innerHTML = "";
        var text = e.clipboardData // handle `paste` event
                   ? e.clipboardData.getData("text/plain") 
                     // use `event.key` of `keydown` event
                     // if defined, else use `e.keyCode`
                   : e.key || String.fromCodePoint(e.keyCode);
        handleInvalid(this, text, e);
      }
      
      function reset() {
        // set `label` `.innerHTML` to empty string
        if (input.value.trim() === "") {
          label.innerHTML = "";
        }
      }

      input.onkeydown = input.onpaste = handleInput;
      input.onfocus = reset;

      try {
        var val = "aaaa";
        handleInvalid(input, val)
      } catch (e) {
        label.innerHTML = e.message;
        alert(input.computedName);
      }
      
    }
  </script>
  <style>
  </style>
</head>
<body>
  <form>
    <input type="number" id="input" />
    <label id="error" for="input"></label>
  </form>
</body>
</html>

plnkr http://plnkr.co/edit/mLgCQfBmvZHb5cNGZWtN?p=preview

于 2016-05-24T07:19:48.043 に答える
0

    function chkValidity(elemementID) {
        var inpObj = document.getElementById(elemementID);
        if (inpObj.checkValidity() == false) {
            inpObj.setCustomValidity("This is not a number or a valid number. And this is my custom validity message for the value "+inpObj.value+" which is being inserted via javascript. Determinig \"required\",\"min\",\"max\" and checkValidity it is enough to do the work.");
          document.getElementById("error").innerHTML = inpObj.validationMessage;
          alert(inpObj.validationMessage);
        } else {
        document.getElementById("error").innerHTML = "This is valid number and within range";
        }
    }
    var value = "aaaa";
    document.getElementById("input").value = value;
    chkValidity("input");
    document.querySelector("#clickme").addEventListener("click", function(){
        chkValidity("input");
    });
    <input type="number" id="input" required min="0" max="9999" step="1" />
    <button id="clickme"> Click Me
    </button>
    <div id="error">
    </div>

于 2016-05-23T20:53:51.960 に答える