HTML5+setCutomValidity of functions validate form instance sharing

  • 2020-06-01 08:14:11
  • OfStack

HTML5 form validation brings convenience to the front-end staff, but there are some defects in the user experience. The default prompt is very unfriendly to the user and cannot accurately obtain the desired information. The good news is that the setCustomValidilty method is customizable when designing the interface. This is a good news, but there are some disadvantages, need to let the opening personnel do some extra processing to achieve the real purpose.

Example 1:


<!DOCTYPE HTML>
<head>
<meta charset="UTF-8">
<title>Html5 Page using javascript Validate the form to judge the input </title>
<script language="javascript">
function check(){
  var pass1=document.getElementbyid("pass1");
  var pass2=document.getElementbyid("pass2");
  if (pass1.value!=pass2.value){
    pass2.setCustomvalidity(" The password is not 1 to ");
  else    
    pass2.setCustomvalidity("");
  }
  var email=document.getElementbyid("email");
  if (!email.checkValidity())
    email.setCustomvalidity(" Please enter the correct one email address ");
}
</script>
</head>
<form id="testForm" onsubmit="return check()">
   password :<input type="password" name="pass1" id="pass1" /><br/>
   Confirm password :<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=" Please enter the code " >
    <button type="submit">Check</button>
  </form>
<script type="text/javascript">
function out(i){
  var v = i.validity;
  if(true === v.valueMessing){
    i.setCustomValidity(" Please fill in some fields ");
  }else{
    if(true === v.patternMismatch){
      i.setCustomValidity(" Please enter the 4 Bit code ");
    }else{
      i.setCustomValidity("");
    }
  }
}
</script>
</body>
</html>

That's all for this article, I hope you enjoy it.


Related articles: