0

我有一个由 validate jquery 插件验证的表单。

<form action="" id="contact-form" class="form-horizontal">
    <fieldset>
        <div class="control-group">
            <label class="control-label" for="name">Nome:</label>
            <div class="controls">
                <input type="text" class="input-xlarge" name="name" id="name" placeholder="Indique o seu nome" />
            </div>
        </div>
        <div class="control-group">
            <label class="control-label" for="email">Email:</label>
            <div class="controls">
                <input type="email" class="input-xlarge" name="email" id="email" placeholder="Indique o seu email" />
            </div>
        </div>
        <!-- ... -->
    </fieldset>
</form>

脚本代码:

$('form#contact-form').validate({
    rules: {
        name: {
            minlength: 2,
            required: true
        },
        email: {
            required: true,
            email: true
        },
        // ...
    },
    highlight: function(label) {
        $(label).closest('.control-group').addClass('error').removeClass('success');
    },
    success: function(label) {
        label.closest('.control-group').addClass('success');
    },
    submitHandler: function(form) {
        $('form#contact-form').slideUp("slow", function() {
            $(this).before('<div class="alert alert-success"><h4>Informação</h4>Mensagem Enviada com sucesso.</div>');
            setTimeout(function () {
                $('#modal').modal('hide');
            }, 3000);
        });
        return false;
    }
});

我有两个问题:

  1. 他们需要的是,当错误得到纠正时,.error 类被删除,生成的标签也被删除。
  2. 我必须放置一个具有具体值的元素的规则是什么,例如数字 8?

当元素包含错误时,代码如下所示:

<div class="control-group error">
    <label class="control-label" for="email">Email:</label>
    <div class="controls">
        <input type="email" class="input-xlarge" name="email" id="email" placeholder="Indique o seu email">
        <label for="email" generated="true" class="error" style="">Por favor introduza um endereço de email válido.</label>
    </div>
</div>

更正错误后,代码如下所示:

<div class="control-group error success">
    <label class="control-label" for="name">Nome:</label>
    <div class="controls">
        <input type="text" class="input-xlarge" name="name" id="name" placeholder="Indique o seu nome">
        <label for="name" generated="true" class="error" style=""></label>
    </div>
</div>
4

1 回答 1

1
  1. 将您的成功功能更改为:

    success: function(label) {
        label.closest('.control-group').removeClass('error').addClass('success');
    }
    

    从 html-tag 中删除 generated=true 参数是不明智的。我过去曾这样做过,它只会给验证功能增加麻烦。

  2. 您可以添加一个方法:

    $.validator.addMethod("equalTo", function(value, element, param) { return (value == param); });
    

    比你的规则:

    name: {
        minlength: 2,
        required: true,
        equalTo: "8"
    } 
    
于 2012-10-12T12:33:31.923 回答