简体   繁体   中英

Changing color of input type date on valid input

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM