Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a red border to an input field along with the required attribute?

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>
like image 878
The Codesee Avatar asked Jan 30 '23 01:01

The Codesee


2 Answers

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>
like image 138
palaѕн Avatar answered Jan 31 '23 14:01

palaѕн


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.

like image 39
jiwopene Avatar answered Jan 31 '23 15:01

jiwopene