相同表单组的JQuery验证和Bootstrap 3 [英] JQuery Validation and Bootstrap 3 for same form-group

查看:89
本文介绍了相同表单组的JQuery验证和Bootstrap 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在问一个有关具有错误"类和复杂对象的问题.

I'm having a question regaring "has-error" class and the complex object.

基本上,对于单个简单类型,它工作得很好,但对于复杂对象,则不能.

Basically for single simple type it works pretty well but for a complex object it doesnt.

我有以下代码:

我的验证

public static MvcHtmlString ValidationErrorFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string error)
{
    if (HasError(htmlHelper, ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData), ExpressionHelper.GetExpressionText(expression)))
        return new MvcHtmlString(error);
    else
        return null;
}


private static bool HasError(this HtmlHelper htmlHelper, ModelMetadata modelMetadata, string expression)
{
    string modelName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(expression);
    FormContext formContext = htmlHelper.ViewContext.FormContext;
    if (formContext == null)
        return false;

    if (!htmlHelper.ViewData.ModelState.ContainsKey(modelName))
        return false;

    ModelState modelState = htmlHelper.ViewData.ModelState[modelName];
    if (modelState == null)
        return false;

    ModelErrorCollection modelErrors = modelState.Errors;
    if (modelErrors == null)
        return false;

    return (modelErrors.Count > 0);
}

JavaScript

Javascript

$.validator.setDefaults({
    highlight: function (element) {
        $(element).closest(".form-group").addClass("has-error");
    },
    unhighlight: function (element) {
        $(element).closest(".form-group").removeClass("has-error");
    }
});

这是我的编辑器模板:

@model DatingWebsite.Models.UserDate

<div class="form-group@(Html.ValidationErrorFor(m=>m, " has-error"))">
    @Html.LabelFor(m=>m.Birthdate, new {@class="col-sm-2 control-label"})
    <div class="col-sm-10">
        @Html.DropDownListFor(model => model.Day, Enumerable.Range(1, 31).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() }), Base.Day, new {@class="form-control" })
        @Html.DropDownListFor( model => model.Month, Enumerable.Range(1, 12).Select(i => new SelectListItem { Value = i.ToString(), Text = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i)}), Base.Month, new {@class="form-control" })
        @Html.DropDownListFor( model => model.Year,  Enumerable.Range(DateTime.Now.AddYears(-80).Year, 80-18).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString()}), Base.Year, new {@class="form-control" })

        @Html.ValidationMessageFor(m => m.Day, null, new { @class = "help-block" })
        @Html.ValidationMessageFor(m => m.Month, null, new { @class = "help-block" })
        @Html.ValidationMessageFor(m => m.Year, null, new { @class = "help-block" })
    </div>
</div>

这是模型:

[Required]
public int Day { get; set; }
[Required]
public int Month { get; set; }
[Required]
public int Year { get; set; }

现在您可以进行验证(m => m),这样我就可以传递整个对象.

Now as you can see for the validation i do (m=>m) so i pass the whole object.

1)如果我什么都没填写但我提交了,我把它们全部变成红色,因此应用了样式,并且我得到了所有红色的错误消息.

1) If i dont fill anything and i submit, i get all of them red, so the style is applied, and i get all error messages in red.

2)我将第一个下拉列表更改为一个值,然后颜色消失,并且不再是红色,尽管我仍然看到其他2条错误消息...

2) I change the first dropdown list to a value, then the color disappears, and it is not red anymore, although i still see the other 2 error messages ...

3)如果我像这样再次提交,它将不会再次变成红色.

3) if i submit again like this then it will not become red again.

注意:我添加的图片不是带有下拉列表的,而是文本框,因为它具有相同的问题.

Note: the pictures i added are not with drop down lists, but textboxes because it has the same problem.

任何人都知道代码有什么问题吗?

Anyone has an idea what is wrong with code?

更新

我注意到,当我向一个文本框添加值时,javascript会调用unheighlight函数并删除has-error类,而另两个文本框则不会调用Highlight函数.

I've noticed that when I add value to one textbox, then the javascript calls unheighlight function and removes the has-error class, and highlight function is not called for the other 2 textboxes.

推荐答案

我只是遇到了同样的问题并找到了解决方案.它不漂亮,但似乎可以正常工作.

I just had the same problem and found a solution. It's not pretty, but it seems to work.

我在form-group div中添加了类multi-validation-group,该类可以包含多个错误消息,然后实现了以下自定义取消突出显示功能,如果没有错误,则仅从form-group div中删除has-error类标签在其中仍然可见.

I've added the class multi-validation-group to my form-group divs that can contain multiple error messages and then implemented the following custom unhighlight function, which only removes the has-error class from the form-group div if no error label remains visible in it.

jQuery.validator.setDefaults({
  errorClass: "has-error",
  highlight: function(element, errorClass, validClass) {
    $(element).closest(".form-group").addClass(errorClass);
  },
  unhighlight: function(element, errorClass, validClass) {
    var group = $(element).closest(".form-group");
    var removeClass = true;

    if (group.hasClass("multi-validation-group")) {
      removeClass = $(group).find("label.has-error:not(:hidden)").length == 0;
    }

    if (removeClass) {
      group.removeClass(errorClass);
    }
  }
});

这篇关于相同表单组的JQuery验证和Bootstrap 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆