首页 > 解决方案 > Is there any way to determine if a time input is partial filled or empty?

问题描述

I've an <input type="time">. Chrome allows the user to partially fill out the input. E.g. user enters hours but no minutes or the other way around. Is there any way using JavaScript to check if that element is empty or is partly filled out?

The value property is empty as long as the input is only filled partly. So that one doesn't work. Is there any property that could be used?

Actually I'm not interested on the partly entered value. Just want to improve user experience by warning that a time without hour or minute is not valid and will be ignored.

JSBin https://jsbin.com/pikabowoyo/edit?html,js,output

let el = document.querySelector('button');
el.addEventListener('click', function() {
  let input = document.querySelector('input');
  console.log(input.value);
});
<input type="time">
<button>show value</button>

标签: javascripthtmldom

解决方案


The time input is invalid if partially filled. If you leave the input empty, and click the button, you'll get an empty value. If you'll half fill the input, and click the button, the input would be marked as invalid.

const el = document.querySelector('button');
el.addEventListener('click', function() {
  const input = document.querySelector('input');
  
  const validity = input.checkValidity();
  
  console.log(validity ? input.value : 'partial');
});
.time:invalid {
  border: 1px solid red;
}
<input type="time" class="time">
<button>show value</button>


推荐阅读