skip to Main Content

I am checking the validity of a required field and it works fine if the field is not disabled. If the input is disabled, it returns true. Is this expected ?

let v1 = $("#i1")[0].checkValidity();
$("#l1")[0].innerHTML = "Validity Before Disabling field:<b>" + v1 + "</b";
$("#i1").prop("readonly", true);
let v2 = $("#i1")[0].checkValidity();
$("#l2")[0].innerHTML = "Validity After  Disabling field:<b>" + v2 + "</b";
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
  <body>
    <div>
    <form>
    Input: <input id="i1" name="i1" required>
    </form>
    <br>
    <label id="l1"></label><br>
    <label id="l2"></label>
    </div>
  </body>
</html>

I was expecting the the input validity to return the correct value irrespective of whether its disabled or not. The same behavior is also seen if the field is set to readonly.

2

Answers


  1. From the MDN documentation, the required field is not applied to read-only fields:

    Note: The required attribute is not permitted on inputs with the readonly attribute specified.

    https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/readonly

    Login or Signup to reply.
  2. required will not apply to readonly or disabled fields.

    From https://stackoverflow.com/a/25694734/12914833 a workaround is to prevent editing with event listeners. However that answer still shows the caret when you tab focus the input, so I’ve fixed that. This should act exactly the same as a readonly input.

    let v1 = $("#i1")[0].checkValidity();
    $("#l1")[0].innerHTML = "Validity Before Disabling field:<b>" + v1 + "</b";
    
    $("#i1").on('keydown paste focus mousedown', function(e){
        if(e.keyCode != 9) // ignore tab
            e.preventDefault();
    });
    $("#i1").css("caret-color","transparent");
    
    let v2 = $("#i1")[0].checkValidity();
    $("#l2")[0].innerHTML = "Validity After  Disabling field:<b>" + v2 + "</b";
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <html>
      <body>
        <div>
        <form>
        Input: <input id="i1" name="i1" required>
        </form>
        <br>
        <label id="l1"></label><br>
        <label id="l2"></label>
        </div>
      </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search