在不使用修剪的情况下检查是否存在空白 [英] Check whether white spaces exist without using trim

查看:84
本文介绍了在不使用修剪的情况下检查是否存在空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码检查日期是否有效. http://jsfiddle.net/uzSU6/36/

I have following code that checks whether date is valid. http://jsfiddle.net/uzSU6/36/

如果日期部分,月份部分或年份部分中有空格,则该日期应被视为无效.为此,当前我正在检查trim操作之前和之后的字符串长度.它工作正常.但是,有没有更好的方法来检查空格? (例如,使用===运算符)

If there is blank spaces in date part, month part or year part the date should be considered invalid. For this, currently I am checking the length of string before and after trim operation. It works fine. However is there a better method to check for white spaces? (For example, using === operator)

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]) );

} 

推荐答案

您可以使用 如果date字符串中有空格,则使用indexOf() 函数.

You can use indexOf() function if there is space in the date string.

if(s.indexOf(' ') != -1)
{
    //space exists
}

这篇关于在不使用修剪的情况下检查是否存在空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆