0

I am creating a form and it has some fields that are compulsory to fill like name and email. I am using the HTML required attribute to enforce that.
<input id="name" type="text" pattern="[a-zA-Z]+" required="required" />

The thing is I am also providing pattern attribute to ensure that I get the correct input. For its styling I am using the following code
input.invalid {
border-color:red;
}

input, input.valid {
border-color: green;
}

But since I am also using the required attribute, it makes the borders red when the form is loaded as the fields are empty at that time. Is there a work around for this or do I have to be just stuck with this?
Any help is appreciated, thanks.

1
  • You can use :required to style the input with required attribute Commented Aug 25, 2021 at 6:04

2 Answers 2

1

input:invalid:focus {
border-color:red;
}

input:valid:focus {
border-color: green;
}
<input id="name" type="text" pattern="[a-zA-Z]+" required="required" />

You can use :focus attribute so that it will not show the red border when it is loaded.

 input:invalid:focus {
   border-color:red;
 }
Sign up to request clarification or add additional context in comments.

Comments

0

As you can see in the below snippet, you can use :required to find the inputs with required attribute and style them

input {
  border: 1px solid #ddd;
  outline: none;
}

input:required {
  border-color: blue;
}

input:invalid {
  border-color: red;
}

input:valid {
  border-color: green;
}
<input id="name" type="text" pattern="[a-zA-Z]+" required="required" />
<input id="name" type="text" pattern="[a-zA-Z]+" />

3 Comments

Why would we need :required, if it is not required it is valid when empty
What I meant to say is there are ways to style the inputs based on different attributes, using them separately or combined together, he can get into a proper solution depends on the requirement.
@Abin Thaha thanks for your answer. The answer you provided will not turn the textbox red if it is empty when the form is submitted. I want it to turn red if it is empty, to indicate the user that they need to fill it, but stay green otherwise. But in your solution it is not turning red if it is empty on submit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.