【问题标题】:How to align the validation errors for radio button and checkbox如何对齐单选按钮和复选框的验证错误
【发布时间】:2013-08-27 12:07:47
【问题描述】:

我在这里使用了验证插件,一切正常,但是单选按钮和复选框显示的错误消息没有正确排列。例如,我在这里使用两个单选按钮进行性别选项。如果未选择任何内容,则会在两个单选按钮之间显示错误消息。列表框也发生了同样的事情。除了这个问题,我尝试了电话号码的范围选项,但我不知道如何正确使用范围选项。帮我解决这个问题。

JS代码:

$(document).ready(function () {
        $.validator.addMethod("validNameCharacter", function (value) {
            var pattern = /^[a-zA-Z0-9]+$/;
            return (pattern.test(value) > 0);
        }, "Avoid Special Characters in User Name");
        $.validator.addMethod("validPasswordCharacter", function (value) {
            var pattern = /^[a-zA-Z0-9]+$/;
            return (pattern.test(value) > 0);
        });
        $.validator.addMethod("ValidSalary", function (value) {
            if (isNaN(value)) {
                return false;
            } else {
                return true;
            }
        }, "Please enter a valid amount");
        var validator = $("#registrationForm").validate({
            errorClass: "error",
            validClass: "valid",
//            onkeyup: true,
//            onblur: true,
//            errorContainer: "#FormValidationErrors",
//            errorLabelContainer: $('ol', "#FormValidationErrors"),
//            wrapper: 'li',
            rules: {
                UserName: {
                    required: true,
                    minlength: 4,
                    maxlength: 15,
                    validNameCharacter: true
                },
                Password: {
                    required: true,
                    minlength: 4,
                    maxlength: 15,
                    validPasswordCharacter: true
                },
                ConfirmPassword: {
                    required: true,
                    minlength: 4,
                    maxlength: 15,
                    validPasswordCharacter: true,
                    equalTo: "#txtPassword"
                },
                EmailId: {
                    required: true,
                    email: true
                },
                Gender: "required",
                DOB: {
                    required: true,
                      date:true
                },
                PhoneNumber: {
                    required: true,
                    range: [1, 10]
                },
                Salary: {
                    ValidSalary: true
                },
                Country: {
                    required: true
                },
                JobAlert: {
                    required: true
                },
                Languages: {
                    required: true
                },
                About: {
                    required: true,
                    minlength: 20,
                    maxlength: 120
                },
                TermsAndConditions: "required"
            },
            messages: {
                UserName: {
                    required: "User Name is Required",
                    minlength: "Please enter atleast 4 characters ",
                    maxlength: "Please enter lessthan fifteen characters"
                },
                Password: {
                    required: "Password is Required",
                    minlength: "Please enter atleast 4 characters ",
                    maxlength: "Please enter less than fifteen characters",
                    validPasswordCharacter: "The Password you entered is invalid"
                },
                ConfirmPassword: {
                    required: "Confirm password is required",
                    minlength: "Please enter atleast 4 characters ",
                    maxlength: "Please enter less than fifteen characters",
                    validPasswordCharacter: "The Password you entered is invalid",
                    equalTo: "Password Does not matches"
                },
                EmailId: {
                    required: "Email is Required",
                    email: "Enter Valid Email"
                },
                Gender: {
                    required: "Please select the Gender"
                },
                DOB:
                {
                    required: "Please enter your Date of birth",
                },
                PhoneNumber: {
                    range: "Enter phone number between 1 to 10 characters"
                },
                Country: {
                    required: "Please select the Country"
                },
                JobAlert: {
                    required: "Please select the Job Alerting type"
                },
                Languages: {
                    required: "Please select the States"
                },
                About: {
                    minlength: "Please enter morethan 20 characters",
                    maxlength: "Please enter lessthan 120 characters"
                },
                TermsAndConditions: "Please Accept It" 
            }
        });
        $(".cancel").click(function () {
            validator.resetForm();
        });
        $("#btnChkValidForm").on('click', function () {
            var status = $("#registrationForm").valid();
            alert("Form  is : " + status + "\nTotal Number of Invalid Fields is : " + validator.numberOfInvalids());
        });

    });

HTML:

   <div id="UserRegistrationContainer" style="background: none repeat scroll 0% 0% slategray; width: 100%; border: 1px solid aqua; border-radius: 11px 11px 11px 11px;" >
    <form  action="/" method="post" id="registrationForm">
    <table>
        <tr>
            <td>
            User Name:
            </td>
            <td>
                <input type="text" name="UserName" value="" />
            </td>
        </tr>
        <tr>
            <td>
            Password:
            </td>
            <td>
                <input type="password" name="Password" value="" id="txtPassword"/>
            </td>
        </tr>
         <tr>
            <td>
           Confirm Password:
            </td>
            <td>
                <input type="password" name="ConfirmPassword" value="" />
            </td>
        </tr>
        <tr>
            <td>
            Mail-ID:
            </td>
            <td>
                <input type="text" name="EmailId" value="" />
            </td>
        </tr>
        <tr>
            <td>
                Gender:
            </td>
            <td>
                <input type="radio" name="Gender" value="Male" /> 
                <label for="Gender">Male</label>
                <input type="radio" name="Gender" value="Female" />
                <label for="Gender" id="genderLabel">Fe Male</label>
            </td>
        </tr>
        <tr>
            <td>
                DOB:
            </td>
            <td>
                <input type="text" name="DOB" value="" id="txtDOB" />
            </td>
        </tr>
        <tr>
            <td>
                Present Salary:
            </td>
            <td>
              <input type="text" name="Salary" value="" />
            </td>
        </tr>
        <tr>
            <td>
                Phone Number:
            </td>
            <td>
                <input type="text" name="PhoneNumber" value="" />
            </td>
        </tr>
        <tr>
            <td>
                Country:
            </td>
            <td>
                <select name="Country">
                    <option value="">Select Country</option>
                    <option value="India">India</option>
                    <option value="Sri Lanka">Sri Lanka</option>
                    <option value="China">China</option>
                    <option value="Japan">Japan</option>
                    <option value="United States">United States</option>
                    <option value="United Kingdom">United Kingdom</option>
                    <option value="Australia">Australia</option>
                    <option value="South Africa">South Africa</option>
                    <option value="Russia">Russia</option>
                </select>
            </td>
        </tr>
        <tr>
            <td>
                    Notify Job Alert:
            </td>
            <td>
                <input type="checkbox" name="JobAlert" value="Email" /> Email <br />
                <input type="checkbox" name="JobAlert" value="Message" /> Message <br />
                <input type="checkbox" name="JobAlert" value="IVR" /> Voice Call <br />
                <input type="checkbox" name="JobAlert" value="Post" />  Post <br />
            </td>
        </tr>
        <tr>
            <td>
                Languages Interested:
            </td>
            <td>
                 <select name="Languages" multiple="multiple" size="5">
                    <option value="C">C</option>
                    <option value="C++">C++</option>
                    <option value="Java">Java</option>
                    <option value="Dot Net">Dot Net</option>
                    <option value="Vxml">Vxml</option>
                    <option value="Perl">Perl</option>
                    <option value="Phython">Phython</option>
                    <option value="HTML5 CSS">HTML5 CSS</option>
                    <option value="Unix">Unix</option>
                </select>
            </td>
        </tr>
          <tr>
            <td>
                About You:
            </td>
            <td>
                <textarea name="About" cols="33" rows="5" style="color:Gray;"></textarea>
            </td>
        </tr>
        <tr>
            <td colspan="3">
                <input type="checkbox" name="TermsAndConditions" value="" class="checkbox" />Accept Terms And Conditions                    
            </td>
        </tr>
        <tr>
            <td style="">
                <input type="submit" id="btnSubmit" value="Submit" name="Submit"/>  
                <input type="reset" id="resetForm" value="Reset" style="margin-left:15px;" class="cancel" />  
                <input type="button" id="btnChkValidForm" value="Check Form" style="margin-left:11px;" />
                <input type="submit" name="Save" value="Save" class="cancel" />
            </td>
        </tr>
    </table>
 </form>
 <div id="FormValidationErrors" class="container" style="margin-left: 325px;color:Red;">

    <ol>
    </ol>
 </div>
</div>

CSS:

.error  {
    background-color: #FFCECE;
    border:solid 1px red;
}
.valid {
    color:black;
}

我的代码链接: 链接 : - http://jsfiddle.net/qHCBy/

【问题讨论】:

    标签: jquery asp.net-mvc performance asp.net-mvc-4 jquery-validate


    【解决方案1】:

    引用OP

    “如果未选择任何内容,则错误消息将显示在两个单选按钮之间。”

    这是默认行为。消息 (&lt;label&gt;) 立即出现在组中的第一个单选或复选框之后。

    您可以使用errorPlacement 回调函数更改其位置。

    先检查它是单选还是复选框,然后相应地定位。

    这是默认回调...

    errorPlacement: function(error, element) {
        error.insertAfter(element);
    }
    

    在您的.validate() 中,执行以下操作...

    errorPlacement: function(error, element) {
        if (element.attr("type") === "radio") {
            // your custom position
        } else {
            error.insertAfter(element);
        }
    }
    

    引用OP

    “除了这个问题,我尝试了电话号码的范围选项,但我不知道如何正确使用范围选项。”

    我真的不确定你的意思,但这就是你使用 range 方法的方式,就像你实现它一样。

    见:http://jqueryvalidation.org/range-method/

    描述:使元素需要给定的值范围。

    使“字段”成为 13 到 23 之间的

    $( "#myform" ).validate({
        rules: {
            field: {
                range: [13, 23]
            }
        }
    });
    

    也许您想要 rangelength 方法代替?

    见:http://jqueryvalidation.org/rangelength-method/

    使“字段”的长度在 2 到 6 个字符之间

    $( "#myform" ).validate({
        rules: {
            field: {
                rangelength: [2, 6]
            }
        }
    });
    

    【讨论】:

    • 感谢您的帮助,我在错误消息对齐方面有另一个查询,这里我知道标签 ID,因此我可以将错误放在标签之后,但是在创建动态控件时如何对齐错误消息。在这种情况下,id 可能会有所不同,对吧?
    • @my1,请把你的话分解成句子......老实说,我无法弄清楚你想问我什么。我可以告诉您,您的errorPlacement 回调函数适用于正在验证的任何元素,因此您不会使用iderror.parent().insertBefore(element); 之类的东西或任何适用的东西。
    • jsfiddle.net/LtAy5 我已经添加了我的代码,因为该验证仅适用于文本框,而不适用于单选按钮、xheckbox 和下拉菜单以及如何解决。你对这些有任何想法吗?
    • @my1,您的 jsFiddle 有两个问题... 1) 您的 select 元素还需要一个唯一的 name 属性。 2) .rules('add') 方法仅适用于在 jQuery .each() 内部的多个元素。
    • $($elm).each(function(){$(this).rules("add", {....});});我试过这个,但表单没有验证它自动提交的任何控件。请发布您的代码
    猜你喜欢
    • 1970-01-01
    • 2018-02-19
    • 2012-01-20
    • 2019-02-02
    • 2011-11-27
    • 2015-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多