.valid()仅使用jQuery Validation插件验证第一个输入

问题描述 投票:6回答:1

我很难让jQuery Validation插件按我的意愿工作。

我所拥有的是一个包含多个必需输入的表单,规则如下所示:

$("#makeEvent").validate({
    onfocusout: false,
    rules: {
        name: {
            required: true,
            minLength: 2,
            maxLength: 100
        },
        host: {
            required: true,
            minLength: 2,
            maxLength: 100
        },
        startDate: {
            required: true,
            date: true
        },
        endDate: {
            required: true,
            date: true
        },
        desc: {
            required: true,
            minLength: 10,
            maxLength: 255
        },
        webpage: {
            required: false,
            url: true
        },
        email: {
            required: true,
            email: true
        },
    }
});

现在我有一个自定义.click()调用,我想验证表单,然后在允许用户发送表单之前显示用户的预览。请参阅以下功能:

$('#submitPreview').click(function() {
    if($("#makeEvent").valid() === false) {
        //What to do if validation fails
    } else if($("#makeEvent").valid() === true) {
        //Show the preview and let the user either make changes or submit the final result
    }
});

但是,该功能仅验证第一个输入(名称),甚至验证它不正确(规则至少需要2个字符,但只输入1个字符时仍然有效。如果根本没有添加任何字符,它只会返回false )。

也许我的方法并不是最好的,所以我对任何建议都持开放态度。如果你想查看凌乱的源代码,你可以在这里看到函数:http://event.gusthlm.se/make.php

jquery jquery-validate
1个回答
20
投票

我可以看到的两个问题是你没有在输入字段中使用name属性,并且你使用name作为其中一个ID(在表单提交时导致IE的各种悲痛)。

我建议将名称属性添加到您的输入,选择和textarea元素并将“name”更改为“thename”之类的内容:

<label for="thename">Börjar</label>
<input type="text" name="thename" id="thename"/>
© www.soinside.com 2019 - 2024. All rights reserved.