表单的验证
表单验证需要CSS和JS相结合来完成
CSS样式
css样式来确定页面所需要的表单元素和样式
<style>
span {
color: red;
font-size: 14px;
display: none
}
;
samp {
color: red;
font-size: 14px;
display: none;
}
</style>
<form action="jhdskj" method="get" οnsubmit=" return show()">
<label>用户名:<input type="text"></label>
<span>*用户名为6-12位</span>
<br>
<label>密码:<input type="password"></label><span>*密码为6位</span><br>
<input type="checkbox" checked><a href="">XXXXXX协议</a><br>
<button disabled>登录</button>
</form>
span中的内容为验证信息,初始条件为:display: none,当文本框中的内容不满足条件时才显现
JavaScript样式
var yh = document.querySelector('input');
var yh1 = document.querySelector('span');
var mm = document.querySelectorAll('input')[1];
var mm1 = document.querySelectorAll('span')[1];
var che = document.querySelectorAll('input')[2];
var but = document.querySelector('button');
but.disabled = !(che.checked);
function show() {
//验证用户名信息
if (!(yh.value.length >= 6 && yh.value.length <= 12)) {
yh1.style.display = 'inline-block';
return false;
}
//验证密码信息
if (!(mm.value.length == 6)) {
mm1.style.display = 'inline-block';
return false;
}
}
che.onchange = function () {
but.disabled = !(this.checked);
submit事件为表单提交事件;当返回值(return)的值为false点击按钮不提交,返回值(return)的值为tru点击按钮提交
//验证用户名信息
if (!(yh.value.length >= 6 && yh.value.length <= 12)) {
yh1.style.display = 'inline-block';
return false;
}
//验证密码信息
if (!(mm.value.length == 6)) {
mm1.style.display = 'inline-block';
return false;
}
disabled属性未必可选,当按钮but.disabled为true时,按钮but不可被点击;当按钮
but.disabled为false时,按钮but才可被点击。
che.onchange = function () {
but.disabled = !(this.checked);