<!doctype html> <html> <head> <meta charset="utf-8"> <title>表单验证1</title> <style> span { font-size: 20px; font-family: "微软雅黑"; font-weight: bold; } #input-text { margin: 0 10px; width: 500px; height: 50px; line-height: 60px; border-radius: 10px; outline: 0; border: 1px solid #999999; } #alert { width: 200px; height: 30px; padding-left: 50px; } #input-submit { background-color: #2F79BA; color: white; font-weight: bold; font-size: 18px; width: 95px; height: 60px; line-height: 60px; border: 0; border-radius: 10px; outline: 0; } </style> <script type="text/javascript"> window.onload = function () { var re = /[\u4e00-\u9fa5a-zA-Z0-9\-]{3,15}/g; var oBtn = document.getElementById('input-submit'); var oInput = document.getElementById('input-text'); var ale = document.getElementById('alert'); oInput.onfocus = function () { ale.innerHTML = "必填,长度为4到16个字符"; } function show() { if ( oInput.value == "") { ale.innerHTML = "姓名不能为空"; } else if (re.test(oInput.value) == True) { ale.innerHTML = "名称格式正确"; } } } </script> </head> <body> <form method="post"> <label><span>名称</span> <input type="text" name="myName" id="input-text"></label> <input type="submit" value="验证" id="input-submit" onclick="show()"> <div id="alert" ></div> </form> </body> </html>