Home >Web Front-end >JS Tutorial >HTML5 setCutomValidity() function validation form example sharing_javascript skills

HTML5 setCutomValidity() function validation form example sharing_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:02:381252browse

HTML5 form validation brings convenience to front-end personnel, but there are some flaws in the user experience. The default prompts are very unfriendly to users and cannot accurately obtain the desired information. Fortunately, the experts provided the setCustomValidilty method to customize the prompt information when designing the interface. This is good news, but there are also some drawbacks, and it requires additional processing by the operator to achieve the truly desired purpose.

Example 1:

<!DOCTYPE HTML>
<head>
<meta charset="UTF-8">
<title>Html5页面使用javascript验证表单判断输入</title>
<script language="javascript">
function check(){
  var pass1=document.getElementbyid("pass1");
  var pass2=document.getElementbyid("pass2");
  if (pass1.value!=pass2.value){
    pass2.setCustomvalidity("密码不一致");
  else    
    pass2.setCustomvalidity("");
  }
  var email=document.getElementbyid("email");
  if (!email.checkValidity())
    email.setCustomvalidity("请输入正确的email地址");
}
</script>
</head>
<form id="testForm" onsubmit="return check()">
  密码:<input type="password" name="pass1" id="pass1" /><br/>
  确认密码:<input type="password" name="pass2" id="pass2" /><br/>
  Email:<input type="email" name="email" id="email" /><br/>
  <input type="submit" />
</form>

Example 2:

<!DOCTYPE html>
<html>
<head>
  <mata charset="utf-8">
  <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){
  var v = i.validity;
  if(true === v.valueMessing){
    i.setCustomValidity("请填写些字段");
  }else{
    if(true === v.patternMismatch){
      i.setCustomValidity("请输入4位数字的代码");
    }else{
      i.setCustomValidity("");
    }
  }
}
</script>
</body>
</html>

The above is the entire content of this article, I hope you all like it.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn