只有在输入被证明不正确后,如何才能使文本字段突出显示为红色?

How can I make a textfield highlight in red only after its input is proven as incorrect?

我有这个表格(我知道,目前非常基础和凌乱。):

这是加载时的样子。

这是我的 CSS:

img {
    position: fixed;
    right: 100px;
    top: 100px;
}

input:invalid {
    background-color : #ff0000;
}

input:valid {
    background-color : #99ff99;
}

我想知道的是,只有当用户因输入错误而返回页面时,如何才能让字段显示为红色?

Here's 带有相关 HTML、CSS 和 JS 的 JSFiddle。

点击提交按钮时,在让用户继续之前检查字段,如果不正确,return false;这样提交按钮就不会刷新页面。

然后对所有错误的元素使用 yourelement.style.backgroundColor = "red";