mat*_*att 88 javascript validation date
我想使用格式验证输入的日期格式mm/dd/yyyy.
我在一个站点中找到了以下代码然后使用它但它不起作用:
function isDate(ExpiryDate) {
var objDate, // date object initialized from the ExpiryDate string
mSeconds, // ExpiryDate in milliseconds
day, // day
month, // month
year; // year
// date length should be 10 characters (no more no less)
if (ExpiryDate.length !== 10) {
return false;
}
// third and sixth character should be '/'
if (ExpiryDate.substring(2, 3) !== '/' || ExpiryDate.substring(5, 6) !== '/') {
return false;
}
// extract month, day and year from the ExpiryDate (expected format is mm/dd/yyyy)
// subtraction will cast variables to integer implicitly (needed
// for !== comparing)
month = ExpiryDate.substring(0, 2) - 1; // because months in JS start from 0
day = ExpiryDate.substring(3, 5) - 0;
year = ExpiryDate.substring(6, 10) - 0;
// test year range
if (year < 1000 || year > 3000) {
return false;
}
// convert ExpiryDate to milliseconds
mSeconds = (new Date(year, month, day)).getTime();
// initialize Date() object from calculated milliseconds
objDate = new Date();
objDate.setTime(mSeconds);
// compare input date and parts from Date() object
// if difference exists then date isn't valid
if (objDate.getFullYear() !== year ||
objDate.getMonth() !== month ||
objDate.getDate() !== day) {
return false;
}
// otherwise return true
return true;
}
function checkDate(){
// define date string to test
var ExpiryDate = document.getElementById(' ExpiryDate').value;
// check date and print message
if (isDate(ExpiryDate)) {
alert('OK');
}
else {
alert('Invalid date format!');
}
}
Run Code Online (Sandbox Code Playgroud)
关于什么可能是错的任何建议?
Eli*_*ing 173
我认为Niklas对你的问题有正确的答案.除此之外,我认为以下日期验证功能更容易阅读:
// Validates that the input string is a valid date formatted as "mm/dd/yyyy"
function isValidDate(dateString)
{
// First check for the pattern
if(!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateString))
return false;
// Parse the date parts to integers
var parts = dateString.split("/");
var day = parseInt(parts[1], 10);
var month = parseInt(parts[0], 10);
var year = parseInt(parts[2], 10);
// Check the ranges of month and year
if(year < 1000 || year > 3000 || month == 0 || month > 12)
return false;
var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
// Adjust for leap years
if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
monthLength[1] = 29;
// Check the range of the day
return day > 0 && day <= monthLength[month - 1];
};
Run Code Online (Sandbox Code Playgroud)
Raz*_*aul 102
我会使用Moment.js进行日期验证.
alert(moment("05/22/2012", 'MM/DD/YYYY',true).isValid()); //true
Run Code Online (Sandbox Code Playgroud)
Jsfiddle:http://jsfiddle.net/q8y9nbu5/
Rav*_*ant 38
使用以下正则表达式来验证:
var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/ ;
if(!(date_regex.test(testDate)))
{
return false;
}
Run Code Online (Sandbox Code Playgroud)
这对MM/dd/yyyy来说很有用.
Mat*_*ija 26
对于这里的懒人我也提供了格式为yyyy-mm-dd的定制版本的功能.
function isValidDate(dateString)
{
// First check for the pattern
var regex_date = /^\d{4}\-\d{1,2}\-\d{1,2}$/;
if(!regex_date.test(dateString))
{
return false;
}
// Parse the date parts to integers
var parts = dateString.split("-");
var day = parseInt(parts[2], 10);
var month = parseInt(parts[1], 10);
var year = parseInt(parts[0], 10);
// Check the ranges of month and year
if(year < 1000 || year > 3000 || month == 0 || month > 12)
{
return false;
}
var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
// Adjust for leap years
if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
{
monthLength[1] = 29;
}
// Check the range of the day
return day > 0 && day <= monthLength[month - 1];
}
Run Code Online (Sandbox Code Playgroud)
Jay*_*ing 13
看到一篇关于这样一个基本主题的帖子这么老,有这么多答案,但没有一个是正确的,这是不寻常的。(我并不是说它们都不起作用。)
Date.parse()不应用于本地日期字符串。MDN说“不建议使用 Date.parse,因为直到 ES5,字符串的解析完全依赖于实现。” 该标准需要(可能是简化的)ISO 8601 字符串;对任何其他格式的支持取决于实现。new Date(string)使用,因为它使用 Date.parse()。这是一个没有隐式转换的高效、简洁的解决方案。它利用了 Date 构造函数将 2018-14-29 解释为 2019-03-01 的意愿。它确实使用了一些现代语言功能,但如果需要,可以轻松删除这些功能。我还包括了一些测试。
function isValidDate(s) {
// Assumes s is "mm/dd/yyyy"
if ( ! /^\d\d\/\d\d\/\d\d\d\d$/.test(s) ) {
return false;
}
const parts = s.split('/').map((p) => parseInt(p, 10));
parts[0] -= 1;
const d = new Date(parts[2], parts[0], parts[1]);
return d.getMonth() === parts[0] && d.getDate() === parts[1] && d.getFullYear() === parts[2];
}
function testValidDate(s) {
console.log(s, isValidDate(s));
}
testValidDate('01/01/2020'); // true
testValidDate('02/29/2020'); // true
testValidDate('02/29/2000'); // true
testValidDate('02/29/1900'); // false
testValidDate('02/29/2019'); // false
testValidDate('01/32/1970'); // false
testValidDate('13/01/1970'); // false
testValidDate('14/29/2018'); // false
testValidDate('1a/2b/3ccc'); // false
testValidDate('1234567890'); // false
testValidDate('aa/bb/cccc'); // false
testValidDate(null); // false
testValidDate(''); // false
Run Code Online (Sandbox Code Playgroud)
use*_*274 12
你可以用 Date.parse()
您可以阅读MDN文档
Date.parse()方法解析日期的字符串表示形式,并返回自1970年1月1日00:00:00 UTC或NaN后的毫秒数(如果字符串无法识别,或者在某些情况下包含非法日期值) (例如2015-02-31).
并检查Date.parseisNaN 的结果
let isValidDate = Date.parse('01/29/1980');
if (isNaN(isValidDate)) {
// when is not valid date logic
return false;
}
// when is valid date logic
Run Code Online (Sandbox Code Playgroud)
请查看建议Date.parse在MDN中使用的时间
Nik*_*las 10
它似乎适用于mm/dd/yyyy格式日期,例如:
http://jsfiddle.net/niklasvh/xfrLm/
我对你的代码唯一的问题是:
var ExpiryDate = document.getElementById(' ExpiryDate').value;
Run Code Online (Sandbox Code Playgroud)
括号内有一个空格,在元素ID之前.将其更改为:
var ExpiryDate = document.getElementById('ExpiryDate').value;
Run Code Online (Sandbox Code Playgroud)
如果没有关于不起作用的数据类型的任何进一步细节,则没有太多可以提供输入的内容.
如果给定的字符串格式正确('MM/DD/YYYY'),该函数将返回true,否则返回false.(我在网上发现这个代码并稍微修改了一下)
function isValidDate(date) {
var temp = date.split('/');
var d = new Date(temp[2] + '/' + temp[0] + '/' + temp[1]);
return (d && (d.getMonth() + 1) == temp[0] && d.getDate() == Number(temp[1]) && d.getFullYear() == Number(temp[2]));
}
console.log(isValidDate('02/28/2015'));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
315450 次 |
| 最近记录: |