最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to make pseudo class :invalid apply to an input AFTER submitting a form - Stack Overflow

programmeradmin6浏览0评论

I have created a form and decided to validate it with just HTML5 and some JS without any additional plugins. So all of my required inputs have required attribute.

Here is the CSS to make them look nice

input:invalid {
    border: 2px solid #c15f5f
}

It sets the border of the invalid inputs to red, even if they haven't been touched yet.

How to make input:invalid apply after clicking submit button, along with the error messages?

I have created a form and decided to validate it with just HTML5 and some JS without any additional plugins. So all of my required inputs have required attribute.

Here is the CSS to make them look nice

input:invalid {
    border: 2px solid #c15f5f
}

It sets the border of the invalid inputs to red, even if they haven't been touched yet.

How to make input:invalid apply after clicking submit button, along with the error messages?

Share Improve this question edited Jan 12, 2017 at 18:07 soundslikeodd 1,0773 gold badges20 silver badges33 bronze badges asked Jan 12, 2017 at 17:32 Jakub MałojłoJakub Małojło 2612 silver badges13 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 15

You can add a class to the form when the submit-button was clicked and adjust your CSS selector so it only matches the input fields in a submitted form:

document.getElementById("submitButton").addEventListener("click", function(){
	document.getElementById("testForm").className="submitted";
});
form.submitted input:invalid{
  border:1px solid red;
}
<form id="testForm">
<input type="text" required>
<input type="submit" value="submit" id="submitButton">
</form>

Building on Thomas' solution and idlefinger's comment, I would suggest listening for the HTML5 invalid event, which fires prior to the submit event.

// save all form controls as variable
var inputs = document.getElementById("your-form").elements;

// Iterate over the form controls
for (i = 0; i < inputs.length; i++) {

  inputs[i].addEventListener("invalid", function(){
    document.getElementById("your-form").className="submitted";

  });
};
form input {
    background: #eee;
}

form.submitted input:invalid {
    background: #ff3b3b;
}
<form id="your-form">
    <input type="text" required>
    <input type="text">
    <input type="submit" value="submit">
</form>

this works for me:

input:invalid:not([value='']) {
    outline: none;
    border: 2px solid #c15f5f;
}

but I prefer using box-shadow rather than border or outline (the default)

发布评论

评论列表(0)

  1. 暂无评论