javascript - 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>
解决方案
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>
推荐阅读
- google-drive-api - 用户可以上传但不能删除共享驱动器上的文件
- docusignapi - 创建第一个签名者指定下一个收件人的信封
- javascript - 如何防止函数将项目重复到 ReactJS 中的对象数组中?
- r - 通过现有对象对数据框进行子集化
- asp.net-mvc - 根据值更改 ASP.NET 视图上的文本
- wso2 - 在 WSO2 IS 中检索和使用来自服务提供商的权限
- sql - 具有不规则日期范围条件的 SQL Server 分组依据
- android - kotlin:如何在 Android 中读取 Uri?
- r - str_replace 定义数量的空格,后跟一个点
- sdk - 项目 SDK(.Net 标准):创建包含 msbuild 目标的 nuget 包的官方方法