//判断输入的内容是否为日期格式
function checkDateFormate(Field) {
var inputDateValue = Field.value
var desc = Field.description
if(inputDateValue == null || inputDateValue == '') {
return false
}
//获取输入字符串的长度
var inputValueLength = inputDateValue.length
//如果满足下面判断的所有条件才算合法的日期,否则不合法
if(checkNumeric(inputDateValue) &&checkLegth(inputValueLength) &&checkSpecialChar(inputDateValue) ) {
return true
}else {
errorMessage("请输入合法的" + desc +"\n类型为日期,格式为YYYY-MM-DD 或者YYYYMMDD")
Field.focus()
return false
}
}
//日期只能是8~10位
function checkLegth(length) {
if(length <8 || length >10) {
return false
}
return true
}
//如果输入的内容中包含‘-’,则按照‘-’分割来去年月日,否则直接按照位数取
function checkSpecialChar(inputDateValue) {
var index = inputDateValue.indexOf('-')
var year = 0
var month = 0
var day = 0
if(index >-1) {
var lastIndex = inputDateValue.lastIndexOf('-')
//只能是YYYY-M-DD或者YYYY-MM-DD的形式
if(lastIndex - index <1 || lastIndex - index >3) {
return false
}
var arrDate = inputDateValue.split('-')
year = arrDate[0]
month = arrDate[1]
day = arrDate[2]
} else {
year = inputDateValue.substring(0,4)
month = inputDateValue.substring(4,6)
day = inputDateValue.substring(6,8)
}
if(Number(month) >12 || Number(day) >31 ||Number(month)<1
|| Number(day)<1 || year.length != 4) {
return false
} else if(day >getLastDayOfMonth(Number(year),Number(month))) {
return false
}
return true
}
//判断输入的内容将‘-’替换成为数字1后,是否全部为数字
function checkNumeric(inputDateValue) {
var replacedValue = inputDateValue.replace(/-/g,'1')
return isNumeric(replacedValue)
}
//判断是否为数字
function isNumeric(strValue)
{
var result = regExpTest(strValue,/\d*[.]?\d*/g)
return result
}
function regExpTest(source,re)
{
var result = false
if(source==null || source=="")
return false
if(source==re.exec(source))
result = true
return result
}
//获得一个月中的最后一天
function getLastDayOfMonth(year,month){
var days=0
switch(month){
case 1: case 3: case 5: case 7: case 8: case 10: case 12: days=31break
case 4: case 6: case 9: case 11: days=30break
case 2: if(isLeapYear(year)) days=29else days=28break
}
return days
}
//判断是否为闰年
function isLeapYear(year){
if((year %4==0 &&year %100!=0) || (year %400==0)) return true
else return false
}
第1步,选中单元格、或者是一个区域,设置为文本格式。
第2步,数据有效性(也叫数据验证)---设置---自定义,
输入这条公式:
=ISNUMBER(FIND("-",A2)*A2)
意思是,用FIND函数在数据中查找减号得到的结果 再乘以原数据,结果必须是数字,才符合要求。
如果这条公式你理解不了的话,给你换个写法:
=AND(ISNUMBER(FIND("-",A2)),ISNUMBER(--A2))
意思是,用FIND在数据中查找减号得到的结果必须是数字,并且该数据通过负负转化后也必须是数字。
这种查错用条件格式更方便直观;
选中区域(以A列为例),选择:开始--条件格式--新建规则;
点击“使用公式确定要设置格式的单元格”;
输入条件公式:=ISTEXT(A1),并设置一种显示格式,比如红色填充;
确定后,非日期型的即会显色。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)