如何在表单验证中替换错误消息

时间:2017-01-12 10:49:15

标签: javascript jquery

我已尝试使用jQuery(".contact_form").validate({ rules: { fname: { required: true, }, lname: { required: true, }, location: { required: true, }, phone: { required: true, }, mail: { required: true, mail: true }, subjct: { required: true, }, message: { required: true, }, }, submitHandler: function (form) { var postData = $(form).serializeArray(); var result = {}; $.each(postData, function () { result[this.name] = this.value; }); return false; } });进行表单验证。

单击“提交”按钮时,空字段将显示错误消息。

我的问题是。我不想要那个错误信息。必须显示每个空场的红色边框。无法了解这一点。

提前致谢



<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<form class="contact_form" method="post">
<div class="row">
<input type="text" class="f_name" name="fname" placeholder="First Name *">
<input type="text" class="l_name" name="lname" placeholder="Last Name">
</div>
<div class="row">
<input type="number" class="phone_number" name="phone" placeholder="Phone Number *">
<input type="email" class="mail_val" name="mail" placeholder="Email ID">
</div>
<div class="row">
<input type="text" placeholder="Subject *" name="subjct" class="subjct_content">
<textarea class="form_textarea" name="message" placeholder="Message *"></textarea>
<input type="submit" value="Submit">
</div>
</form>
&#13;
{{1}}
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

尝试以下

jQuery(".contact_form").validate({
        rules: {
            fname: {
                required: true,
            },
            lname: {
                required: true,
            },
            location: {
                required: true,
            },
            phone: {
                required: true,
            },
            mail: {
                required: true,
                mail: true
            },
            subjct: {
                required: true,
            },
            message: {
                required: true,
            },
        },
        submitHandler: function (form) {
            var postData = $(form).serializeArray();
            var result = {};
            $.each(postData, function () {
                result[this.name] = this.value;
            });
            return false;
        },
       errorPlacement: function(error,element) {
            return true;
         }
    });

或者您只需将错误标签/范围设置为以下样式

即可
display:none

答案 1 :(得分:0)

要将红色标记为空框,您可以在validate功能中添加以下内容:

    invalidHandler: function(form, validator) {
               $('form input,textarea').each(function(){
                   if($(this).val() == ""){
                    $(this).css('border', '1px solid red'); 
                   }
               });
            }, 

    errorPlacement: function(){
                return false;  // suppresses error message text
            }