验证按键上的日期不起作用

时间:2014-10-24 00:12:50

标签: javascript jquery regex

这是正则表达式:

 pattern =/^([0-9]{2})-([0-9]{2})-([0-9]{4})$/;

大家好,我发现日期格式的简单正则表达式,没有检查闰年,但在我的小提琴上,我仍然可以输入其他无效字符。 请参阅我的FIDDLE

1 个答案:

答案 0 :(得分:2)

http://jsbin.com/ruhaxo/9/edit

你的代码让我有点不舒服,所以我试着写这个更简单,这样你会更容易阅读,你可以拿出你需要的部分,我认为这只是event.preventDefault()什么时候有比赛。只是为了展开:http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes你正在寻找字符代码而不是字面数字。

    $('input').on('keypress', function (e) {
      var leng = $(this).val().length;

      if (window.event) {
        code = e.keyCode;
      }else {
        code = e.which;
      };

      var allowedCharacters = [49,50,51,52,53,54,55,56,57,48,45];
      var isValidInput = false;

      for (var i = allowedCharacters.length - 1; i >= 0; i--) {
        if(allowedCharacters[i] == code){
          isValidInput = true;
        } 
      };

      if(isValidInput === false || /* Can only input 1,2,3,4,5,6,7,8,9 or - */
       (code == 45 && (leng < 2 || leng > 5 || leng == 3 || leng == 4)) ||
       ((leng == 2 || leng == 5) && code !== 45) || /* only can hit a - for 3rd pos. */
        leng == 10 ) /* only want 10 characters "12-45-7890" */
      {

        event.preventDefault();
        return;
      }

    });

您也可以使用对象而不是数组来执行此操作。这更容易阅读:

    $('input').on('keypress', function (e) {
      var leng = $(this).val().length;

      if (window.event) {
        code = e.keyCode;
      }else {
        code = e.which;
      };

      var allowedCharacters = {49:1,50:2,51:3,52:4,53:5,54:6,55:7,56:8,57:9,48:0,45:'-'}; /* KeyCodes for 1,2,3,4,5,6,7,8,9,- */

      if(typeof allowedCharacters[code] === 'undefined'|| /* Can only input 1,2,3,4,5,6,7,8,9 or - */
         (code == 45 && (leng < 2 || leng > 5 || leng == 3 || leng == 4)) ||
         ((leng == 2 || leng == 5) && code !== 45) || /* only can hit a - for 3rd pos. */
          leng == 10 ) /* only want 10 characters "12-45-7890" */
      {

        event.preventDefault();
        return;
      }

    });

编辑:

请注意这一点,我还没有对此进行全面测试,但是如果除上述其他选项之外还有其他选项,我还会从上述帖子编辑正则表达式(这在其他检查后发生在keyup上)已经制作了这将验证日期格式mm-dd-yyyy请检查它是否正常工作,我尝试了02-29-2008,我能想到的第一个闰年,它有效,但我建议测试它更多,因为它已被修改。

$('input').on('keyup',function(e){

  /* From:
  http://stackoverflow.com/questions/17503043/javascript-regular-expression-to-validate-date-in-mm-dd-yyyy-format
  and
  http://jsfiddle.net/LSsMc/
  */

  var thisVal = $(this).val();
  var leng = thisVal.length;

  var reg = new RegExp(/^(((0[13578]|1[02])\-(0[1-9]|[12]\d|3[01])\-((19|[2-9]\d)\d{2}))|((0[13456789]|1[012])\-(0[1-9]|[12]\d|30)\-((19|[2-9]\d)\d{2}))|(02\-(0[1-9]|1\d|2[0-8])\-((19|[2-9]\d)\d{2}))|(02\-29\-((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/g);
  if(leng == 10){
    if(reg.test(thisVal)){
      console.log('Valid Date');
    }else {
      event.preventDefault();
      return;
    } 
  }
});