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

javascript - Changing color of input type date on valid input - Stack Overflow

programmeradmin5浏览0评论

So for my regular input type="text" field I use the following code to change the color to green, only after something has been typed in and it is valid:

input[type="text"]:not(:placeholder-shown):valid {
 background-color: green;
}

Is there any way to the same for an input type="date" field?

 <input type="date" class="form-control calender-black" name="dbfield52">

The problem seems to be it already is valid since it shows: DD-MM-YYYY as standard value.

Is there a way to do this with css only selectors? Or else maybe with javascript.

So for my regular input type="text" field I use the following code to change the color to green, only after something has been typed in and it is valid:

input[type="text"]:not(:placeholder-shown):valid {
 background-color: green;
}

Is there any way to the same for an input type="date" field?

 <input type="date" class="form-control calender-black" name="dbfield52">

The problem seems to be it already is valid since it shows: DD-MM-YYYY as standard value.

Is there a way to do this with css only selectors? Or else maybe with javascript.

Share Improve this question asked Jun 22, 2020 at 11:57 SybrentjuhSybrentjuh 2875 silver badges17 bronze badges 1
  • Please do also show how you bind the calendar to the input. I believe you do it in JQuery – Tharavink Prasad Sivarajan Commented Jun 22, 2020 at 12:00
Add a ment  | 

2 Answers 2

Reset to default 4

You can do this easily using :valid css pseudo-class like:

input[type="date"]:valid {
  border: 2px solid green;
}

Demo:
( Just select a value from control and it will add a green border to the date control )

/* This is just used to set some styling */
input[type="date"] { padding: .375rem .75rem;font-size: 1rem;line-height: 1.5;border-radius: .25rem;border: 2px solid #ced4da; }
input[type="date"]:focus { outline: 0; }

/* This is the important part */
input[type="date"]:valid {
  border: 2px solid green;
}
<form>
  <input type="date" class="form-control calender-black" 
     name="dbfield52" required /><br/>
  <p>
    <button>Submit</button>
  </p>
</form>

You have to set the input as required in order for validation to work:

input[type="date"]:valid {
  background-color: green;
}
<input type="date" class="form-control calender-black" name="dbfield52" required>

发布评论

评论列表(0)

  1. 暂无评论