Javascript – setCustomValidity is not a function

htmljavascriptjqueryvalidation

This is the simple code I run hoping to get control over html5 validation but the browser says setCustomvalidity is not a function. what am I doing wrong?

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Untitled Document</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>

<body>
    <input type='text' id='tocheck' />
    <script>
        $("#tocheck").click(function () {
            var $this = $(this);
            $this.setCustomValidity("slkdjf");
        });
    </script>
</body>
</html>

Best Solution

jQuery does not have the setCustomValidity function, but the actual DOM element does. The jQuery selector always returns an Array, so you can use the zero index to get the actual DOM element or you can just use this (not $(this)) to get the DOM element upon which you can set the custom validity.

 <!doctype html>

    <html>
    <head>

    <meta charset="utf-8">
    <title>Untitled Document</title>


    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

   </head>

  <body>
      <form>
      <input type='text' id='tocheck'/>
      <button>
      Submit
      </button>
      </form>
      <script>
       $("#tocheck").click(function(){
            this.setCustomValidity("slkdjf");
       });
     </script>
  </body>