Currently if an input field with the required
attribute is empty, it will display the browser's default error message. If I remove this attribute, it will display a red border on the input field because of my JavaScript code. How would I display both at the same time?
$("form").submit(function(e) {
e.preventDefault();
var title = document.getElementById('title');
if (!title.value) {
title.classList.add('error');
setTimeout(function() {
title.classList.remove('error');
}, 300);
}
});
.error {
position: relative;
animation: shake .1s linear;
animation-iteration-count: 3;
border: 1px solid red;
}
@keyframes shake {
0% {
left: -5px;
}
100% {
right: -5px;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="title">
<input type="submit">
</form>
You can implement it like this:
$("form").submit(function(e) {
e.preventDefault();
// ....
});
$("form input").on("invalid", function(event) {
$('#title').addClass('error');
setTimeout(function() {
$('#title').removeClass('error');
}, 500);
});
.error {
position: relative;
animation: shake .1s linear;
animation-iteration-count: 3;
border: 1px solid red;
outline: none;
}
@keyframes shake {
0% {
left: -5px;
}
100% {
right: -5px;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="title" required>
<input type="submit">
</form>
Use the CSS.
It is better to use it also for invalid fields (text in type=number
field or any other invalid value).
@keyframes shake3 {
0% {left: -5px}
16% {left: 5px}
33% {left: -5px}
49% {left: 5px}
66% {left: -5px}
80% {left: 5px}
100% {left: 0}
} /* And @keyframes with prefixes */
input:invalid {
border: 2px solid red;
animation-name: shake3;
animation-duration: .4s;
position: relative;
}
<input required >
If you want to show it only when you want, replace input:invalid
by .submited input:invalid
and add the .submited
class to your form to activate styles.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With