Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display HTML5 error message/validation on hidden radio/checkbox

Tags:

html

css

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>
like image 328
universal Avatar asked Apr 06 '18 07:04

universal


1 Answers

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>
like image 151
Jignesh Raval Avatar answered Nov 05 '22 12:11

Jignesh Raval