0

I'm looking to give my form inputs a red border they are invalid when the form submits. Currently I have achieved this by using the input:invalid selectors in CSS; however, this makes it so that the red borders appear from the start, even before the user types anything into the inputs fields. What I'm looking for is to not have any red borders until the form is submitted and only red borders for the invalid inputs that prevent the form from a successful submission. I am working with Vue.js on this and my code is below.

input,
textarea {
  font-size: 14px;
  padding: 7px;
  filter: none;
  &[type='email'],
  &[type='password'],
  &[type='text'],
  &[type='search'] {
    height: 20px;
    font-family: inherit;
    font-weight: bold;
    border: 1.4px solid white;
    border-radius: 3px;
    background: #fff;
    color: #002169;
    transition: all 0.3s;
    &:invalid {
      border: 1.4px solid rgb(255, 18, 18);
    }
    &::placeholder {
      color: #0378a6;
      opacity: 1;
    }
  }
}
albert_anthony6
  • 594
  • 2
  • 9
  • 30
  • If possible post your code in codesandbox. Only css is available above – Stark Buttowski Jul 16 '20 at 14:37
  • 1
    well, you could do `:focus:invalid {.. styles ...}` so the red outline would only appear when the cursor is in the input field. Also, I believe blank is NOT considered invalid by the browser as long as the input doesn't have `required` on it. – Bryce Howitson Jul 16 '20 at 14:40
  • The inputs do have required on them so they are red when they're empty. And focus:invalid isn't really what I'm after. Is there any other way I could get the same affect for invalid inputs but only after the users attempts to submit the form? – albert_anthony6 Jul 16 '20 at 14:43
  • The reason :focus:invalid wouldn't suffice is because it's good up until the user unfocuses from the input and the border goes away even though it could still be invalid and on submit, no red border would appear even if some were invalid. – albert_anthony6 Jul 16 '20 at 14:46

1 Answers1

0

If the user clicks on the submit-button, it will trigger an event that check your form-field.

<input type="submit" value="Send" @click="checkForm()">

or

<form onsubmit="return checkForm();">

When everything is right, send. If something is wrong, prevent sending and add a class to every input-field that is wrong. Your class have the css rules of :invalid above.

You can find more information about form validation with javaScript on this post.

klediooo
  • 630
  • 1
  • 7
  • 25