如何显示基于无效输入SASS的span



我使用SASS,我想在输入无效时显示错误跨度,这可以使用SASS吗?

这是输入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>
);
};

这是SASS文件我可以自己更改输入字段的边框颜色但是我不知道如何在输入无效时将span的显示从none更改为block

.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;
}
}
}

输入使用带有regex和所需属性的HTML模式进行验证这样的:

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,
},
]

我找到了一种方法来做到这一点,首先你必须确保span位于输入的后面,就像这样

<div className="formInput">
<input
{...inputProps}
onChange={onChange}
onBlur={handleFocus}
onFocus={() =>
inputProps.name === "confirmPassword" && setFocused(true)
}
focused={focused.toString()}
className="Input"
/>
<span>{errorMessage}</span>
</div>

,然后添加到SCSS文件:

.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;
}**
}
}
}

是的,你可以用伪类来做就像下面的例子,你需要把span标签放在输入标签旁边,这里我使用的是文本输入元素但你可以根据需要改变它:

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: '✓';
}

在这里,如果用户将此输入字段保留为空,则内容将更改。

最新更新