2021-04-27 更新

实际使用时发现,通过 onsubmit 返回函数值进行表单校验,返回函数不能放在 $(document).ready(function(){}$(function(){}) 的函数体中,会报错找不到该函数。


前端提交请求时,对于 ajax ,可以在请求之前做数据校验;对于传统的 form 表单提交,则可以使用它自带的一个事件 onsubmit 进行绑定校验。

以下是标准表单( table 布局,默认引入 jQuery ):

<form action="?" method="post" name="form1" onsubmit="return check();">
    <table align="center" width="420px" cellPadding="2" cellSpacing="1" bgcolor="#A4B6D7" style="word-wrap:Break-word;">
        <tr style="cursor: hand;background:#d7e3f6">
            <td width="20%" align="right">条型码</td>
            <td><input style="width:90%" type="text" name="GOODSNUM" size="30"  maxlength="8" ></td>
        </tr>
        <tr>
            <td align="center" colspan="2">
                <input type="submit" name="save" value="保存" />
            </td>
        </tr>
    </table>
</form>
<script type="text/javascript">
function check() {
var code = $('input[type="text"][name="GOODSNUM"]').val();
if (!code) {
alert("请填写条形码!");
return false;
}
}
</script>

在点击提交按钮(type = submit)时,触发 form 表单的 onsubmit 事件。可以在回调方法中做校验,不通过返回 false 即可。

当然还有另一个种形式:

<form action="?" method="post" name="form1">
    <table align="center" width="420px" cellPadding="2" cellSpacing="1" bgcolor="#A4B6D7" style="word-wrap:Break-word;">
        <tr style="cursor: hand;background:#d7e3f6">
            <td width="20%" align="right">条型码</td>
            <td><input style="width:90%" type="text" name="GOODSNUM" size="30"  maxlength="8" ></td>
        </tr>
        <tr>
            <td align="center" colspan="2">
                <input type="button" name="save" value="保存" onclick="return check(this);"/>
            </td>
        </tr>
    </table>
</form>
<script type="text/javascript">
function check(that) {
...
that.form.submit();
}
</script>

没有提交按钮,在普通按钮的点击事件回调方法中做校验,校验通过了,再调用 form 表单的 submit() 方法,手动提交表单。

this.form.submit();。需要注意的是,使用该方法提交时,在当前表单中不能存在 name = submit 的项,否则表单会提交失败(form.submit() 不能提交表单的原因)。

当两种 form 方法同时存在时,会出现很多情况。当提交按钮类型为 submit 时,点击按钮,只执行点击事件的回调方法(猜测点击事件优先级大于提交本身);当提交按钮类型为 button 时,依然只执行点击事件的回调方法。测试环境为 win7 Google Chrome 最新版本 75.0.3770.100(正式版本) (64 位)。测试代码如下:

<html lang="zh-CN">
<head>
    <title>form 表单提交验证</title>
</head>
<body>
<form action="?" method="post" name="form1" onsubmit="return check(1);">
    <table align="center" width="420px" cellPadding="2" cellSpacing="1" bgcolor="#A4B6D7" style="word-wrap:Break-word;">
        <tr style="cursor: hand;background:#d7e3f6">
            <td width="20%" align="right">条型码</td>
            <td><input style="width:90%" type="text" name="GOODSNUM" size="30"  maxlength="8" ></td>
        </tr>
        <tr>
            <td align="center" colspan="2">
                <input type="submit" name="save" value="保存" onclick="return check(2);"/>
            </td>
        </tr>
    </table>
</form>
<script type="text/javascript">
    function check(num) {
        console.log(num);
        return false;
    }
</script>
</body>
</html>
文章目录