如何检查格式是否有效?

时间:2016-01-08 06:20:22

标签: javascript jquery css

我有这个样本:

link

代码HTML:

<input class="" type="text" name="primary_phone" id="primary_phone" maxlength="10" placeholder="1234567890">

CODE CSS:

.valid{
  border:1px solid green;
}
.invalid{
  border:1px solid red;
}

CODE JS:

$( "#primary_phone" ).blur(function() {
        text = $(this).val().replace(/(\d\d\d)(\d\d\d)(\d\d\d\d)/, '($1)$2-$3');
        $(this).val(text);

    if(the form==valid)
    {
       addClass.(valid);
    }else{
      addClass.(invalid);
   }

});

我想要做的是验证你的...添加一个红色边框,以防它拼写错误且格式不受尊重。

我在代码中提出了我想做的事情 如果用户首先键入正确的表单然后删除并写错了,我想使代码无效。

如果您需要更多信息,请告诉我

提前致谢!

2 个答案:

答案 0 :(得分:1)

制作(.替换:),查看this

:valid{
  border:1px solid green;
}
:invalid{
  border:1px solid red;
}

<input class="" type="text" name="primary_phone" id="primary_phone" maxlength="10" placeholder="1234567890" pattern="(\d\d\d)(\d\d\d)(\d\d\d\d)">

pattern属性添加为(\d\d\d)(\d\d\d)(\d\d\d\d),以便浏览器知道什么是valid,什么是invalid

检查此更新的fiddle

答案 1 :(得分:0)

您可以regex.test()检查格式是否有效,如下所示。如果格式有效,它将返回true,如果无效,则返回false

$("#primary_phone").blur(function() {
  var text = $(this).val();
  if(text.length==13) return;
  
  var isValid = /(\d\d\d)(\d\d\d)(\d\d\d\d)/.test(text);
  if (isValid) {
    $(this).val(text.replace(/(\d\d\d)(\d\d\d)(\d\d\d\d)/, '($1)$2-$3'));
    $(this).addClass('valid').removeClass('invalid');
  } else {
    $(this).addClass('invalid').removeClass('valid');
  }
});
.valid {
  border: 1px solid green;
}

.invalid {
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="" type="text" name="primary_phone" id="primary_phone" maxlength="10" placeholder="1234567890">