javascript中怎么设置from提交前的数据验证

JavaScript010

javascript中怎么设置from提交前的数据验证,第1张

form表单的数据先由js判断处理,通过后再提交数据到后台。

1、js获取表单数据,根据实际情况判断是否符合规则。一般的判断是否为空,是否含有不安全字符,有就过滤掉(这一步也可以在后台处理)。

2、对于未通过的输入,向用户返回信息提示。

3、验证通过,提交数据到后台。

4、根据实际需求做处理.....

下面是一个简单的例子:

<form id="loginForm" action="" method="post">

    用户名: <input id="username" name="username" type="text" maxlength="16" />

    <br />

    <input id="go" type="button" value="提交" />

</form>

<script>

    var loginForm = document.getElementById('loginForm')

    var go = document.getElementById('go')

    go.onclick = function(){

        var username = loginForm.username.value

        //这里判断了用户名的输入不能为空,且长度为6-16位

        if(username && (typeof(username)!='undefined') && (username!=0) && (username.length>=6) && (username.length<=16)){

            //验证通过,提交表单数据

            loginForm.submit()

        }else{

            alert('输入不符合规则')

        }

    }

</script>

通常要先在前端对数据做处理得情况下,并不是用<input type="submit" />按钮,而是用<input type="button" />按钮,因为要先对数据进行处理再提交到后台;对于数据的判断验证,大多是使用正则表达式来判断的,虽然比较麻烦,不过如今浏览器对html5的兼容则省掉不少麻烦,新增的 input 类型可以满足一般的需求。

function userCheck() {

//申明变量获取输入的值

var username = document.form1.username.value

var password = document.form1.password.value

if(username=="") {

window.alert("用户名不能为空。")

document.form1.username.focus()

return false

}if(username=="abc") {

window.alert("用户名不能为空。")

document.form1.username.focus()

return false

}

if(password==""){

window.alert("请输入密码")

document.form1.password.focus()

return false

} if(password=="123"){

window.alert("密码错误")

document.form1.password.focus()

return false

}} <form method="post" name="form1" action="servlet/LoginServlets">

<center>

<p> <table width="225" border="1" bordercolor="#00FF00">

<tr>

<td width="64"><div align="center">登陆名:</div></td>

<td colspan="2">

<div align="left">

<input type="text" name="username" title="请输入登陆名" />

</div></td></tr>

<tr>

<td><div align="center">密 码:</div></td>

<td colspan="2">

<div align="left">

<input type="password" name="password" size="21" title="请输入密码">

</div></td></tr>

<tr><tr>

<td colspan="2"><div align="center">

<input name="button" type="button" onClick="userCheck()" value="登陆" />

</div></td>

<td><div align="center">

<input name="reset" type="reset" onClick="quxiao()" value="取消" />

</div></td>

</tr>

</table>

使用JS进行判断

<html>

<head>

<title>判断单选框为必选</title>

<meta charset="UTF-8"/>

</head>

<body>

<form name="from1">

<p>请选择你的性别</p>

<input type="radio" id="b" name="sex" value="1">男 

        <input type="radio" id="g" name="sex" value="2">女  

        <br />

        <button type="button" onclick="check()">确定</button>

</form>

<script type="text/javascript">

function check(){

if(!document.getElementById("b").checked && !document.getElementById("g").checked){

   alert("必须选择性别!")

   return false

   }

}

</script>

</body>

</html>