js实现表单验证-完整代码

 一、页面展示

 

二、全部代码

页面代码

<body>
  <div id="container">

    <!--主体开始 -->
    <div id="register">
      <form onsubmit="return check()" action="register_success.html">
        <fieldset>
          <legend>新用户注册</legend>
          <p>
            <label>用户名:</label>
            <input name="" type="text" id="txtName" class="txt" onblur="checkName()" />
            <span id="span_name">由英文字母和数字组成的4-16位字符,以字母开头</span>
          </p>
          <p>
            <label>密码:</label>
            <input name="" type="password" id="txtPwd" class="txt" onblur="checkPwd()" />
            <span id="span_pwd">由英文字母和数字组成的4—10位字符。</span>
          </p>
          <p>
            <label>确认密码:</label>
            <input name="" type="password" id="txtConfirmPwd" class="txt" onblur="checkPwd2()" />
            <span id="span_confirmPwd"></span>
          </p>
          <p>
            <label>电子邮箱:</label>
            <input name="" type="text" id="txtEmail" class="txt" onblur="checkEmail()" />
            <span id="span_email">邮箱账号@域名,如:good@tom.com</span>
          </p>
          <p>
            <label>手机号码:</label>
            <input name="" type="text" id="txtPhone" class="txt" onblur="checkNum()" />
            <span id="span_phone">手机号由11位数字组成,且以13、15、18开头</span>
          </p>
          <p>
            <label>出生日期:</label>
            <input name="" type="text" id="txtBornDate" class="txt" onblur="checkBirthday()" />
            <span id="span_Born">出生日期在1900~2009之间,如:1985-3-1或1985-03-01</span>
          </p>
          <p>
            <label>所在城市:</label>
            <select id="selProvince" required>
              <option value="">请先选择城市</option>
              <option value="0">湖南省</option>
              <option value="1">湖北省</option>
              <option value="2">浙江省</option>
            </select>
            <select id="selCity" required></select>
          </p>
          <p>
            <input type="submit" value="提交" class="btn" />
          </p>
        </fieldset>
      </form>
    </div>

css代码 -- 外部css

@charset "utf-8";   /* 编码格式 utf-8*/

/*表单*/
#register{
	height:450px;
	margin-top:20px;
	border:0px solid red;
}

div#register fieldset {
	border: 1px solid #039;
	width: 700px;
	padding: 20px;
	margin:0px auto;
}

div#register fieldset legend {
	margin-left: 20px;
	font-weight:bold;
	color:#039;
}

div#register p{
	font-size:14px;
	margin-top:20px;
}

div#register label {
	width: 100px;
	display: block;
	float: left;
	text-align: right;
}

div#register .txt {
	border: 1px solid #ccc;
	width: 130px;
	height:18px;
}

div#register span {
	color: #999;
}
.wrong{
	color:red;
}
p .btn{
	width:80px;
	height:30px;
	background-color:#039;
	text-align:center;
	margin-left:50px;
	color:#fff;
	border:0;
}
p .btn:hover{
	background-color:#d73b25;
}

/*版权*/
#footer{
	height:100px;
	border:0px solid green;
	background-color:#039;
}

#footer p{
	color: #ffffff;
	font-size: 12px;
	text-align: center;
	line-height: 20px;
	padding-top:30px;
}

js代码   这个 写在 body 里面即可 最下面

<script>     
let $secondLi = $('.secondLi')
      $secondLi.hover(
        function () {
          $(this).children("ul").stop().slideDown(1000)
        },
        function () {
          $(this).children("ul").stop().slideUp(1000)
        })

      // 城市
      let arr = new Array();

      arr['0'] = ['长沙市', '株洲市', '湘潭市'];
      arr['1'] = ['武汉市', '黄岗市', '汉口市', '荆门市', '孝感市'];
      arr['2'] = ['杭州市', '台州市', '临安市', '宁波市'];


      $('#selProvince').change(function () {

        //获取到城市的下拉列表框
        let $city = $('#selCity');
        //先去清空原有的列表内容
        $city.html('')
        let arrList = arr[$(this).val()];
        let str = ''
        for (var i = 0; i < arrList.length; i++) {
          str += '<option value=' + arrList[i] + '>' + arrList[i] + '</option>';
        }
        $city.html(str);
      });

</<script> 

 引用外部  js 文件 



function  checkName() {  //验证用户名
	let userName=document.getElementById("txtName").value
	let name_prompt=document.getElementById("span_name")
	let nameReg=/^[a-zA-Z][a-zA-Z0-9]{3,15}$/
	if(!nameReg.test(userName)){
		name_prompt.style.background=''
		name_prompt.style.color='red'
		name_prompt.innerHTML="错误,用户名应由英文字母和数字组成的4-16位字符,以字母开头"
		
		return false
	}else{
		name_prompt.style.background='url(./images/li_ok.gif) no-repeat'
		name_prompt.style.color='transparent'
			return true
	}
}

function checkEmail(){   //验证邮箱
	let txtemail =document.getElementById("txtEmail").value
	let span_email =document.getElementById("span_email")
	let emailReg=/^\w{3,}(\.\w+)*@[A-z0-9]+(\.[A-z]{2,5}){1,2}$/
	if(!emailReg.test(txtemail)){
		span_email.style.color='red'
		span_email.style.background=''
		span_email.innerHTML='错误,邮箱格式不对'
		return false
	}else{
		span_email.style.background='url(./images/li_ok.gif) no-repeat'
		span_email.style.color='transparent'
		return true
	}
}

function checkPwd(){  //验证密码
	let txtPwd=document.getElementById("txtPwd").value;
	let span_pwd=document.getElementById("span_pwd");
	 let pwdReg=/[A-z0-9]{4,10}/;
	 if(!pwdReg.test(txtPwd)){
		span_pwd.style.background=''
		span_pwd.style.color='red'
	 	span_pwd.innerHTML='错误,密码不对'
		return false
	 }else{
		
	 	span_pwd.style.background='url(./images/li_ok.gif) no-repeat'
		 span_pwd.style.color='transparent'
	 	return true
	 }
}
function checkPwd2(){
	let txtPwd=document.getElementById("txtPwd").value
	  let txtPwd2=document.getElementById("txtConfirmPwd").value
	  let  span_pwd2=document.getElementById("span_confirmPwd")
	    if(txtPwd2!=txtPwd){
			span_pwd2.style.color='red'
			span_pwd2.style.background=''
			span_pwd2.innerHTML="错误,密码与上一个不同"
			return false
		}else{
			span_pwd2.style.background='url(./images/li_ok.gif) no-repeat'
			span_pwd2.style.color='transparent'
			return true
		}
}

function checkNum(){
	   let txtNum=document.getElementById('txtPhone').value
	   let  span_Num=document.getElementById("span_phone")
	    let numReg=/^1[358][0-9]{9}/
		if(!numReg.test(txtNum)){
			span_Num.style.background=''
			span_Num.innerHTML="错误,手机号码格式不对"
			span_Num.style.color='red'
			return false
		}else{
			span_Num.style.background='url(./images/li_ok.gif) no-repeat'
			span_Num.style.color='transparent'
			return true
}
}
function checkBirthday(){
	 let txtBirthday =document.getElementById('txtBornDate').value
	 let span_Birthday=document.getElementById('span_Born')
	 let BirthdayReg=/^((19\d{2})|(200\d))-(0?[1-9]|1[0-2])-(0?[1-9]|[1-2]\d|3[0-1])$/
	 if(!BirthdayReg.test(txtBirthday)){
		span_Birthday.style.background=''
		span_Birthday.style.color='red'
		 span_Birthday.innerHTML="错误,出生日期在1900-2009之间:如:1985-3-1或1985-03-01"
		 return false
	 }else{
		span_Birthday.style.background='url(./images/li_ok.gif) no-repeat'
		span_Birthday.style.color='transparent'
		 return true;
	 }
}
function check(){
	if(checkName()&&checkNick()&&checkEmail()&&checkPwd()&&checkPwd2()&&checkNum()&&checkBirthday()){
		return true
	}else{
		return false
	}
}

  • 7
    点赞
  • 70
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,以下是一个简单的 JavaScript 表单验证的示例代码: ```html <form id="myForm"> <label for="username">用户名:</label> <input type="text" id="username" name="username"><br> <label for="password">密码:</label> <input type="password" id="password" name="password"><br> <label for="email">邮箱:</label> <input type="email" id="email" name="email"><br> <button type="submit">提交</button> </form> <script> const form = document.querySelector('#myForm'); const username = document.querySelector('#username'); const password = document.querySelector('#password'); const email = document.querySelector('#email'); form.addEventListener('submit', function(e) { e.preventDefault(); // 阻止表单默认提交行为 if (username.value.trim() === '') { alert('用户名不能为空'); username.focus(); return false; } if (password.value.trim() === '') { alert('密码不能为空'); password.focus(); return false; } if (email.value.trim() === '') { alert('邮箱不能为空'); email.focus(); return false; } if (!isValidEmail(email.value.trim())) { alert('邮箱格式不正确'); email.focus(); return false; } // 验证通过,可以提交表单了 form.submit(); }); function isValidEmail(email) { // 简单判断邮箱格式是否正确 return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email); } </script> ``` 这段代码会对表单中的用户名、密码、邮箱进行验证,确保这些字段不能为空,且邮箱格式正确。如果验证失败,会弹出提示框并将焦点聚焦到该字段,阻止表单提交;如果验证通过,则允许表单提交。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刚子最爱编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值