我有以下代码检查日期是否有效.http://jsfiddle.net/uzSU6/36/
如果日期部分,月份部分或年份部分中有空格,则该日期应视为无效.为此,目前我正在检查trim操作前后字符串的长度.它工作正常.但是有没有更好的方法来检查空格?(例如,使用===运算符)
function isValidDate(s)
{
var bits = s.split('/');
//Javascript month starts at zero
var d = new Date(bits[2], bits[0] - 1, bits[1]);
if ( isNaN( Number(bits[2]) ) )
{
//Year is not valid number
return false;
}
if ( Number(bits[2]) < 1 )
{
//Year should be greater than zero
return false;
}
//If there is unwanted blank space, return false
if ( ( bits[2].length != $.trim(bits[2]).length ) ||
( bits[1].length != $.trim(bits[1]).length ) ||
( bits[0].length != $.trim(bits[0]).length ) )
{
return false;
}
//1. Check whether the year is a Number
//2. Check whether the date parts are eqaul to original date components
//3. Check whether d is valid
return d && ( (d.getMonth() + 1) == bits[0]) && (d.getDate() == Number(bits[1]) );
}
Run Code Online (Sandbox Code Playgroud)
如果字符串中有空格,则可以使用indexOf()函数date.
if(s.indexOf(' ') != -1)
{
//space exists
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
957 次 |
| 最近记录: |