Reputation: 1496
I want to have my :invalid
or :required
selector to be invisible until submitting.
The example of my question shown below:
input[type=text]:invalid {
border: red solid 1px;
}
<figure class="fig">
<label>
<div class="order">4</div>
<p>If the Answer to Question 2 is Yes How Many Blocks are
included (A Form Should be Completed for Each Block)
<span class="asterisk">*</span>
</p>
</label>
<br>
<input type="text" name="number_of_blocks"
placeholder="Enter number of blocks"
required="required">
<br>
</figure>
The :invalid
pseudoclass is already visible before I start to fill the form, which doesn't look nice.
How can I make it only becombe visible after submission?
I found something here:
Form hidden field and required validation use
Though this was not was I was looking for, as it doesn't contain the CSS I'm searching for.
Upvotes: 0
Views: 520
Reputation: 32002
You'll have to use JavaScript to loop through all the input fields and check the validity of each one.
$('#form').on('submit', function(e) {
var isValid = true;
$('input', $(this)).each(function() {
if (!$(this)[0].checkValidity()) {
isValid = false;
$(this).addClass('invalid');
}
})
return isValid;
})
.invalid {
border: red solid 1px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form" novalidate>
<figure class="fig">
<label>
<div class="order">4</div>
<p>If the Answer to Question 2 is Yes How Many Blocks are Included (A Form Should be Completed for Each Block)<span class="asterisk">*</span></p>
</label>
<br>
<input type="text" name="number_of_blocks" placeholder="Enter number of blocks" required="required">
<br>
</figure>
<button>Submit form</button>
</form>
Upvotes: 1