使用.valid()时使用规则和消息的jQuery Validation插件

时间:2014-07-22 05:26:14

标签: jquery validation jquery-validate

使用jQuery验证插件时,使用.valid()时使用规则和方法的正确方法是什么。我之前习惯使用.validate(),但由于我必须在表单外部保留一个按钮,因此我不得不切换到使用.valid()。但是现在,我没有像之前那样获得那些自定义错误消息。我该如何做到这一点?

我怀疑,我使用.valid()的方式是错误的。我尝试了很多东西,但都失败了。

<!DOCTYPE HTML>
<html>
<head>

<title>Test Validation Plugin</title>

<script type="text/javascript" src="/resources/scripts/jq.js"></script>
<script type="text/javascript" src="/resources/scripts/temp.js"></script>
<script type="text/javascript" src="/resources/scripts/validate.js"></script>

<body>
    <form id="createAccount">
        <input type="text" class="titlea" name="titlea" value="" autocomplete="off">
        <label for="titlea" generated="true" class="error titlea" style=""></label>

        <br>
        <br>

        <input type="text" class="titleb" name="titleb" value="" autocomplete="off">
        <label for="titleb" generated="true" class="error titleb" style=""></label>

    </form>

    <br>

    <button id="btn">Process</button>

</body>
</html>

jQuery代码

$('#btn').click(function() {
    rules: {
        titlea: {
            required: true,
            minlength: 5,
            maxlength: 24
        },
        titleb: {
            required: true,
            minlength: 5,
            maxlength: 24
        },
    },
    messages: {
        titlea: {
            required: 'Please choose a title',
            minlength: 'Title A should be at least 5 characters',
            maxlength: 'Title A cannot exceed 24 characters'
        },
        titleb: {
            required: 'Please choose a title',
            minlength: 'Title B should be at least 5 characters',
            maxlength: 'Title B cannot exceed 24 characters'
        },
    }

    ('#createAccount').valid() { // Is this where the problem is?
        // Submit the form using jQuery ajax
    }
});

1 个答案:

答案 0 :(得分:1)

有很多语法问题,应该是

//register the validator
$('#createAccount').validate({
    rules: {
        titlea: {
            required: true,
            minlength: 5,
            maxlength: 24
        },
        titleb: {
            required: true,
            minlength: 5,
            maxlength: 24
        },
    },
    messages: {
        titlea: {
            required: 'Please choose a title',
            minlength: 'Title A should be at least 5 characters',
            maxlength: 'Title A cannot exceed 24 characters'
        },
        titleb: {
            required: 'Please choose a title',
            minlength: 'Title B should be at least 5 characters',
            maxlength: 'Title B cannot exceed 24 characters'
        },
    }
});

$('#btn').click(function (e) {
    //check validate
    if ($('#createAccount').valid()) {
        e.preventDefault()
    }
});