Heim  >  Artikel  >  Web-Frontend  >  HTML5+setCutomValidity()函数验证表单实例分享_javascript技巧

HTML5+setCutomValidity()函数验证表单实例分享_javascript技巧

WBOY
WBOYOriginal
2016-05-16 16:02:381153Durchsuche

HTML5表单验证给前端人员带来了便利,但是在用户体验上存在一些缺陷,默认的提示对用户很不友好,无法准确的获取想要的信息。好在大牛们在接口设计的时候提供了setCustomValidilty方法可以自定义提示信息。这是一个好消息,但也存在一些弊端,需要让开人员做额外的一些处理才达到真正想要的目的。

示例一:

<!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>

示例二:

<!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>

以上所述就是本文的全部内容了,希望大家能够喜欢。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn