0

Why is a hidden input not considerd 'valid' by the jquery selector and what can I do about that (i.e. to make it valid).

console.log($("#a").is(":valid")); // true
console.log($("#b").is(":valid")); // false
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="a" type="text" value="abc">
<input id="b" type="hidden" value="def">

1
  • 1
    because :valid is a CSS property with certain rules. It's not validating the input as you might expect. It only affects non hidden inputs, since hidden inputs can't be changed by the user and can therefore not be "not valid" Commented May 6, 2020 at 11:58

2 Answers 2

2

As per the MDN:

Hidden inputs don't participate in constraint validation; they have no real value to be constrained.

And as such will not receive any valid or invalid pseudoclasses. A couple of options come to mind, either filter the collection to exclude hidden inputs or use this check as a workaround:

$("#b").is(":not(:invalid)");
Sign up to request clarification or add additional context in comments.

Comments

1

console.log($("#a").is(":valid")); // true
console.log($("#b").is(":valid")); // false
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="a" type="text" value="abc">
<input id="b" type="text" style="display:none" value="def">

Change type from hidden to text, then use CSS to change the display property to none

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.