最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Capture HTML error input validation when set in javascript (shows a warn) or check validation before - Stack Overflow

programmeradmin2浏览0评论

I am trying validate a data to set in an input. I want to use HTML validation.

For example, I want to check if "aaaa" is a valid data for an number input. I wanted use willValidate or validity but I can not set an invalid value, the console shows (Chrome):

The specified value "aaaa" is not a valid number. The value must match to the following regular expression: -?(\d+|\d+.\d+|.\d+)([eE][-+]?\d+)?

I have tried catch the error but it is not an Exception. I retrieve the input value and it is empty after the error.

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

See JSFiddle Demo

I want to check if a value to set is valid in the input type. I thought set the invalid value in the input and check willValidate or validity but the browser shows a warn and the input value is empty. The problem is that my frontend set the inputs values via JavaScript but the user pass the values. When an error occurs I need show the error to the user and not put only and input empty.

I know that the warn is not an Exception. I want know shows the error when set an invalid input value in any type.

I am trying validate a data to set in an input. I want to use HTML validation.

For example, I want to check if "aaaa" is a valid data for an number input. I wanted use willValidate or validity but I can not set an invalid value, the console shows (Chrome):

The specified value "aaaa" is not a valid number. The value must match to the following regular expression: -?(\d+|\d+.\d+|.\d+)([eE][-+]?\d+)?

I have tried catch the error but it is not an Exception. I retrieve the input value and it is empty after the error.

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

See JSFiddle Demo

I want to check if a value to set is valid in the input type. I thought set the invalid value in the input and check willValidate or validity but the browser shows a warn and the input value is empty. The problem is that my frontend set the inputs values via JavaScript but the user pass the values. When an error occurs I need show the error to the user and not put only and input empty.

I know that the warn is not an Exception. I want know shows the error when set an invalid input value in any type.

Share Improve this question edited Jan 24, 2023 at 20:09 TylerH 21.1k79 gold badges79 silver badges114 bronze badges asked May 20, 2016 at 11:23 SnakeDrakSnakeDrak 3,6424 gold badges29 silver badges44 bronze badges 2
  • Essentially you want to test for a value-rejection, rather than an error? (I'm not sure there will be an event related to this, but I just wanted to clarify for my own understanding.) – David Thomas Commented May 23, 2016 at 6:17
  • I want to check if a value to setted is valid in the input type. I thought set the invalid value in the input and check willValidate or validity but the browser shows a warn and the input value is empty. The problem is that my frontend set the inputs values via javascript but the user pass the values. When an error occurs I need show the error to the user and not put only and input empty... – SnakeDrak Commented May 23, 2016 at 6:31
Add a ment  | 

4 Answers 4

Reset to default 1 +100
var value = "aaaa";
document.getElementById("input").value = value;
if (document.getElementById("input").value == null || document.getElementById("input").value == "") {
        alert("Invalid value");
}

    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>

To check value being set by JavaScript, you can throw an Error, having .message set to warning displayed in the console, to catch if the input value does not match the same Regular Expression displayed in the console.

To check user input you can use onkeydown and onpaste events; use the <label> element to display message in your HTML, onfocus event to set the label's .innerHTML to empty string if the input value is empty an string.

Note, the message displayed in the console is also set at the input element's putedName property; though is not updated at user input and set to empty string following an alert() at the time of the 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, "putedName:", el.ptedName);
        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.putedName);
      }
      
    }
  </script>
  <style>
  </style>
</head>
<body>
  <form>
    <input type="number" id="input" />
    <label id="error" for="input"></label>
  </form>
</body>
</html>

Here is a Plnkr example: https://plnkr.co/edit/mLgCQfBmvZHb5cNGZWtN?p=preview

It's because that's not an error but only a warning. You can check that in the console.

What you can do is check for isNaN(value)and throw an Error object.

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 as example

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论