2018-06-04
使用JS完成注册页面表单校验
一、步骤实现
第一步:确定事件(onsubmit)并为其绑定一个函数
第二步:书写这个函数(获取用户输入的数据<获取数据时需要在指定位置定义一个 id>)
第三步:对用户输入的数据进行判断
第四步:数据合法(让表单提交)
第五步:数据非法(给出错误提示信息,不让表单提交)
问题:如何控制表单提交?
关于事件 onsubmit:一般用于表单提交的位置,那么需要在定义函数的时候给出一个 返回值。 如:onsubmit = return checkForm()
二、代码实现
JS代码:
<script> ?
function checkForm(){ ?
//alert("aa"); ??/**校验用户名*/ ? //1.获取用户输入的数据 ? var uValue = document.getElementById("user").value; ?
//alert(uValue); ??if(uValue==""){ ???//2.给出错误提示信息 ??? alert("用户名不能为空!"); ? return false;} ?????
/*校验密码*/ ?? var pValue = document.getElementById("password").value;
?if(pValue==""){ ??
alert("密码不能为空!"); ?? return false; ??} ?????/**校验确认密码*/ ? var rpValue = document.getElementById("repassword").value;
? if(rpValue!=pValue){ ?
alert("两次密码输入不一致!"); ?? return false; ??} ?????/*校验邮箱*/ ? var eValue = document.getElementById("eamil").value;
??if(!/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z09_-])+/.test(eValue)){
???alert("邮箱格式不正确!"); ??? return false; ?
} ?
?}
</script>
Html 部分:
<form action="#" method="get" name="regForm" onsubmit="return checkForm()">
需要在指定位置添加 id
第一阶段:前端开发_使用JS完成注册页面表单校验
原文地址:https://www.cnblogs.com/sunNoI/p/9131715.html