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
From the MDN documentation, the
required
field is not applied toread-only
fields:https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/readonly
required
will not apply toreadonly
ordisabled
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.