HTML5

1个成员

html5 JavaScript表单验证实现方法

发表于 2017-02-02 4095 次查看

<!doctype html>
<html lang="en">
<head>
<meta charset=utf-8 />
<title>html5 网页特效表单验证实现方法</title>
<style>
body {
  font-family: "helvetica", arial, helvetica;
}
label {
  display: block;
  float: left;
  clear: left;
  text-align: right;
  width: 100px;
  margin-right: 10px;
}

div { padding: 10px; }

fieldset { border: 1px solid #ccc; margin-bottom: 20px; }

</style>
<script>

var form = document.getelementsbytagname('form')[0];
form.onsubmit = function (event) {
  for (var key in event) {
    dump(key + ' = ' + event[key] + '');
  }
 
  var i = this.length, el;
  while (i--, el = this[i]) {
    if (el.willvalidate) dump([el.id, el.validity.valid]);
  }

  return false;
};

form.oninvalid = function (event) {
  dump([].slice.call(event, 0));
  // alert('was not valid');
};

function dump(obj) {
  document.getelementbyid('debug').innerhtml += '<pre>' + json.stringify(obj) + '</pre>';
}
</script>
</head>
<body>
<form>
  <fieldset>
    <legend>round one</legend>
    <div><label for="email">email:</label> <input novalidate id="email" name="email" type="email" /></div>

    <div><label for="url">homepage:</label><input id="url" type="url" name="url" required /></div>
    <input type="submit" class="savestate" value="save" formnovalidate></input>  
  </fieldset>

  <fieldset>
    <legend>round two</legend>
    <div><label for="email2">email:</label> <input id="email2" name="email" type="email" /></div>
    <div><label for="url2">homepage:</label><input id="url2" type="url" name="url" required /></div>   
    <input type="submit" class="savestate" value="save" formnovalidate></input>  
  </fieldset>

  <input type="submit" />
</form>
<div id="debug"></div>

</body>
</html>

发表回复
你还没有登录,请先登录注册