浅谈form表单的各种校验,如何阻止form表单的提交,form表单和ajax请求的混合使用

本文介绍了一个注册功能中使用的HTML表单及JavaScript验证方法,确保所有字段完整,身份证和电话号码长度正确,并检查身份证号码的唯一性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1:在做注册功能时,不会写比较复杂的正则,同时又不想写大量的js校验函数,还想用form表单向后台发送数据,这时候form表单的校验功能就能派上用场了,form表单完整代码如下

		<form id="reg-form" action="Patient/pregpa" method="post" >
				<table>
					<tr>
						<td>姓名</td>
						<td><input type="text" name="name" id="name"></td>
					</tr>
					<tr>
						<td>身份证号</td>
						<td><input type="text" name="identification" id="identification" "checkidcard()"> </td>
					</tr>
					<tr>
						<td>性别</td>
						<td style="text-align: left"> &nbsp;&nbsp;
							<select name="sex" class="select" id="sex" style="width: 60px;height: 25px">
							<option value="男">男</option>
							<option value="女" >女</option>
						</select></td>
					</tr>
					<tr>
						<td>年龄</td>
						<td><input type="text" name="age" id="age"></td>
					</tr>
					<tr>
						<td>联系电话</td>
						<td><input  type="text" name="tel" id="tel">
						</td>
					</tr>
					<tr>
						<td>密码</td>
						<td><input type="password" name="password" id="password"></td>
					</tr>
					<tr>
						<td>家庭住址</td>
						<td><input type="text" name="address" id="address"></td>
					</tr>													
				</table>
				<div class="buttons">
					<input value="注册" type="submit" style="margin-right:20px; margin-top:20px;" "return f()">
					<a href="plogin.html" style="margin-right:45px; margin-top:20px;">已有账号,我要登录</a>
				</div>
				<br class="clear">
			</form>

说明:这里我要做的校验主要有三个,1:所有的提交参数都不能为空,2:身份证和手机号码必须长度固定,3:验证身份证号码是否已经存在。为了让form表单校验不通过就不提交,大家千万记得给submit一个函数返回值,下面是完整的js函数代码

<script type="text/javascript">
		function f(){
			var name=$("#name").val();
			var identification=$("#identification").val();
			var tel=$("#tel").val();
			var age=$("#age").val();
			var address=$("#address").val();
			var password=$("#password").val();

			if(name==null||name==""||age==null||age==""||address==null||address==""||password==null||password==""){
				alert("注册信息不全,请填写完整信息");
				return false;
			}if(identification.length!=18){
				alert("请填写18位正确的身份证号")
				return false;
			}if(tel.length!=11){
				alert("请填写11位正确手机号码")
				return false;
			}
				return true;
		}

		function checkidcard(){
			var identification=$("#identification").val();
			$.get("Patient/idcard?identification="+identification,function(data){
				if(data == 'error'){
					alert('身份证已存在,不能重复注册');
					return false;
				}
			});
		}

	</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值