<!DOCTYPE html>
<html>
<head>
  <mata charset="gb2312">
  <title>form test</title>
</head>
 
<body>
  <form name="test" action="." method="post">
    <input type="text" required pattern="^\d{4}$" oninput="out(this,'输入四位数数字')" placeholder="请输入代码" >
    <button type="submit">Check</button>
  </form>
<script type="text/javascript">
function out(i,tip){
  var v = i.validity;
  if(true === v.valueMessing){//非空验证
    i.setCustomValidity("请填写些字段");
  }else{
    if(true === v.patternMismatch){//规则验证
      i.setCustomValidity(tip);
    }else{
      i.setCustomValidity("");
    }
  }
}
</script>
</body>
</html>