jQuery输入验证

时间:2015-03-23 21:41:49

标签: javascript html forms input

我正在努力确保我的表单上的输入不是空的。我使用jQuery检查输入,但它不检查输入。提交按钮允许它通过:

<form id="preenrollment-airlines" name="preenrollment-airlines" class="tn-form-conversion" method="post" action="#" onSubmit="return(validate());">
<div class="form-col">
    <input id="firstName" name="firstName" onFocus="if (this.value=='firstName') this.value = ''" type="text" placeholder="First name*">
</div>
<div class="form-col">
    <input id="lastName" type="text" name="lastName" onfocus="if (this.value=='lastName') this.value = ''" type="text" placeholder="Last name*" />
</div>
<div class="form-col">
    <input id="addr" type="text" name="address" onfocus="if (this.value=='address') this.value = ''" type="text" placeholder="Address*" />
</div>
<div class="form-col">
    <input id="city" type="text" name="city" onfocus="if (this.value=='city') this.value = ''" type="text" placeholder="City*" />
</div>
<div class="form-col">
    <input id="zip" type="text" name="postalCode" onfocus="if (this.value=='postalCode') this.value = ''" type="text" placeholder="Postal Code*" />
</div>
<div class="form-col">
    <input id="dm" type="text" name="dm" onfocus="if (this.value=='dm') this.value = ''" type="text" placeholder="DM # * (Bottom left corner of your letter)" id="dm" />
</div>
<div class="form-col">
    <input id="email" type="text" name="email" onfocus="if (this.value=='email') this.value = ''" type="text" placeholder="Email*" />
</div>
<div class="form-col">
    <input type="text" name="digits" onfocus="if (this.value=='digits') this.value = ''" type="text" placeholder="Last 4 digits of current BMO AIR MILES World credit card*" id="digits" />
</div>
</div>
<div class="clear"></div>
<input type="hidden" name="formName" id="formName_id" value="preenrollment-airlines" />
<div style="clear: both;">
    <br />
    <div style="text-align: center;">
        <input id="submit" style="margin-top: 25px;" class="primary button" type="submit" value="Submit" />
    </div>
</div>

这是我到目前为止的javascript:


    $(document).ready(function () {
        $('#preenrollment-airlines input').blur(function () {
            if ($(this).val().length === 0) {
                $(this).parents('input').addClass('warning');
            }
        });
    });

我不知道从哪里开始。我无法使用任何插件进行验证,因此我需要检查输入是否为空,然后我可以为其添加一个类。

1 个答案:

答案 0 :(得分:0)

您希望捕获Submit事件以防止表单发送。在此功能中,您可以检查以确保输入全部有效。

有关提交事件以及如何使用jQuery捕获它的更多信息, view the docs here