Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
699 views
in Technique[技术] by (71.8m points)

css - Display HTML5 error message/validation on hidden radio/checkbox

I have CSS-customized radio buttons, which have required validation. The default radio buttons are hidden by CSS rule.

When I submit the form, the default validation message is also hidden.

Form looks like this CSS customized radio buttons

How can I display default error message (like: Please select one of the options) while disabling radio buttons? (Pure HTML/CSS without using Js)

input[type="radio"] {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  visibility: hidden;
}

input[type="radio"]:checked +label {
  border: 1px solid blue;
}
<h3>Gender</h3>

<input id="male" type="radio" name="gender" value="male" required>
<label for="male">Male</label>

<input id="female" type="radio" name="gender" value="female" required>
<label for="female">Female</label>

<input id="other" type="radio" name="gender" value="other" required>
<label for="other">Rather not to say</label>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

as @joostS said, hidden radio button will not trigger native error message. for that we need to hide it using opacity. I have created sample example.

Also it will not trigger validation until we submit the form by clicking on submit button. If you need validation on "onChange" event of any form elements, then we need to use jQuery or Javascript solution to achieve that.

I hope it will be helpful.

label {
display: inline-block;
border: 2px solid #83d0f2;
padding: 10px;
border-radius: 3px;
position: relative;
}

input[type="radio"] {
  opacity: 0;
position: absolute;
z-index: -1;
}

input[type="radio"]:checked +label {
  border: 1px solid #4CAF50;
}

input[type="radio"]:invalid +label {
  
}
<h3>Gender</h3>
<form>


<input id="male" type="radio" name="gender" value="male" required> 
<label for="male">Male</label>


<input id="female" type="radio" name="gender" value="female" required> 
<label for="female">Female</label>


<input id="other" type="radio" name="gender" value="other" required>
<label for="other">Child</label>

<input type="submit" />
</form>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...