im using SASS and i would like to display an error span when the input is invalid, can this be done using just SASS?
this is the input div:
const FormInput = (props) => {
const [focused, setFocused] = useState(false);
const { label, errorMessage, onChange, id, ...inputProps } = props;
const handleFocus = (e) => {
setFocused(true);
};
return (
<div className="formInput">
<span>{errorMessage}</span>
<input
{...inputProps}
onChange={onChange}
onBlur={handleFocus}
onFocus={() =>
inputProps.name === "confirmPassword" && setFocused(true)
}
focused={focused.toString()}
className="Input"
/>
</div>
);
};
and this is the SASS file i can change the border color of the input field it self but idk how to change the display of the span from none to block when the input is invalid
.formInput {
display: flex;
flex-direction: column;
width: 90%;
height: max-content;
span {
color: red;
font-size: 13px;
display: none;
padding: 0.5rem 0;
}
.Input {
border: none;
outline: none;
background-color: var(--inputColor);
border-radius: 8px;
padding: 20px;
&:invalid[focused="true"] {
border: 1px solid red;
}
}
}
the inputs are validated using html pattern with regex and required attribute like this:
const inputs = [
{
id: 1,
name: "email",
type: "email",
placeholder: "Email",
errorMessage: "It should be a valid email address!",
label: "Email",
required: true,
},
{
id: 2,
name: "password",
type: "password",
placeholder: "Password",
errorMessage:
"Password should be 8-20 characters and include at least 1 letter, 1 number and 1 special character!",
label: "Password",
pattern: `/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/`,
required: true,
},
]
CodePudding user response:
I found a way to do this, first you have to make sure that the span is placed after the input like this
<div className="formInput">
<input
{...inputProps}
onChange={onChange}
onBlur={handleFocus}
onFocus={() =>
inputProps.name === "confirmPassword" && setFocused(true)
}
focused={focused.toString()}
className="Input"
/>
<span>{errorMessage}</span>
</div>
and then add this to the SCSS file:
.Input {
border: none;
outline: none;
background-color: var(--inputColor);
border-radius: 8px;
padding: 20px;
&:invalid[focused="true"] {
border: 1px solid red;
}
&:invalid[focused="true"] {
display: block;
**~ {
span {
display: block;
}**
}
}
}
CodePudding user response:
Yeah, you can do it with pseudo class like the following example, you need to put the span tag just next to the input tag, here I'm using a text input element but you can change it as you require:
HTML
<input name="question1" type="text" value="prefixed value" required> <span></span>
CSS
input[type="text"]:invalid span:after {
content: '✖';
}
input[type="text"]:valid span:after {
content: '✓';
}
Here the content will change if the person leave this input field empty.