允许Backspace验证日期格式

时间:2014-07-08 13:28:38

标签: javascript

在下面的Javascript代码中,我正在验证退格键和删除键不起作用的日期格式。

function AcceptDateCharacters(event, separator) {

    var keyCode = event.which ? event.which : event.keyCode;
    if((separator.length != 1) && (keyCode > 8 && keyCode < 45))  
    {
        return false;
    }
    //lets allow digits
    var expression = "^[0-9";

    //lets allow the separator character
    expression += separator;

    //lets complete the expression
    expression += "]$";

    var regex = new RegExp(expression);
    return AcceptRegExOnly(event, regex)
   // var keyCode = event.which ? event.which : event.keyCode;
   //if ((keyCode >8 && keyCode <= 45))
    return true; 
};

1 个答案:

答案 0 :(得分:0)

你不能只为退格和删除添加if语句吗?

  function AcceptDateCharacters(event, separator) {

        var keyCode = event.which ? event.which : event.keyCode;
        if((separator.length != 1) && (keyCode > 8 && keyCode < 45))  
        {
            return false;
        }
// added conditional
        if(keyCode == 8 || keyCode == 46){
            return true;
        }
        //lets allow digits
        var expression = "^[0-9";

        //lets allow the separator character
        expression += separator;

        //lets complete the expression
        expression += "]$";

        var regex = new RegExp(expression);
        return AcceptRegExOnly(event, regex)
       // var keyCode = event.which ? event.which : event.keyCode;
       //if ((keyCode >8 && keyCode <= 45))
        return true; 
    };