1.要求代码实现如下:
“账号”和“密码”为必填项且自动获得光标焦点;
设置“密码”由字母开头,长度为6-10,仅包含数字,字母和下划线;
“邮箱”检查其格式的合法性。
代码如下:
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>登录表单</title><style>span{color:red;font-weight: bold;}</style></head><body><form action="" id="myForm"><p>账号:<input type="text" id="username" autofocus="autofocus" onkeyup="checkUserName(this)"/> <span><i class="error">*</i></span></p><p>密码:<input type="text" id="password" autofocus="autofocus" onkeyup="checkPassword(this)"/><span><i class="error">*</i></span></p><p>邮箱:<input type="text" id="email" onkeyup="checkEmail(this)"/><span><i class="error">*</i></span></p><p style="margin-left: 50px;"><input type="submit" value="提交"/> <input type="reset" value="重置" /></p></form><script>function checkUserName(obj){var length=obj.value.length;var label=obj.parentElement.getElementsByClassName("error")[0];if(length>0){label.textContent="通过验证";return true;}else{label.textContent="账号为必填项";return false;}}function checkPassword(obj){var length=obj.value.length;var label=obj.parentElement.getElementsByClassName("error")[0];if(length>0){var re1 = /^[a-zA-Z]\w{5,9}$/;if(re1.test(obj.value)){label.textContent="密码正确!";}else{label.textContent="密码由小写字母开头,长度为6-10,仅包含数字,字母和下划线!";}"通过验证!";return true; }else{label.textContent="密码为必填项";return false;}}function checkEmail(obj){var length=obj.value.length;var label=obj.parentElement.getElementsByClassName("error")[0];var re2 = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;if(re2.test(obj.value)){label.textContent="邮箱合法!";return true;}else{label.textContent="邮箱不合法!";return false;}}myForm.onsubmit=()=>{var f1=checkUserName(username);var f2=checkPassword(password);var f3=checkEmail(email);return f1&&f2&&f3;}</script></body>
</html>
效果图如下: