Best approach for extending unobtrusive javascript in MVC3 to add a style to a div client side

只愿长相守 提交于 2019-12-02 17:40:52
Germán

The $.validator.setDefaults method solved this issue for me with Bootstrap from Twitter. I'm usingjquery.validate.js and jquery.validate.unobtrusive.js.

Since unobtrusive validation on DOM ready scans your document and caches unobtrusive validation options for each form it encounters, it is needed to call the $.validator.setDefaults method before document scan occurs.

// setup defaults for $.validator outside domReady handler
$.validator.setDefaults({
    highlight: function (element) {
        $(element).closest(".clearfix").addClass("error");
    },
    unhighlight: function (element) {
        $(element).closest(".clearfix").removeClass("error");
    }
});

$(document).ready(function() {
       // do other stuff
});

Came accross the same issue. I am tackling it by adding and extesion to the HtmlHelper Class.

This is what I did for the ValidationSummary:

   public static class TwitterBootstrapHelperExtensions
    {
        public static MvcHtmlString BootstrapValidationSummary(this HtmlHelper helper,
                               bool excludePropertyErrors,
                               string message)
        {
            if(helper.ViewData.ModelState.Values.All(v => v.Errors.Count == 0)) return new MvcHtmlString(string.Empty);

            string errorsList = "<ul>";
            foreach (var error in helper.ViewData.ModelState.Values.Where(v => v.Errors.Count >0))
            {
                errorsList += string.Format("<li>{0}</li>", error.Errors.First().ErrorMessage);
            }
            errorsList += "</ul>";
            return new MvcHtmlString(string.Format("<div class=\"alert-message error\"><span>{0}</span>{1}</div>",message,errorsList));

        }
    }

And in the .cshtml file I replace Html.ValidationSummary with this:

@Html.BootstrapValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.")

Remember to add the namespance of your extension class in the views folder web.config file.

I will post here later if I tackle the individual input item before you. HTH

Rather than reinventing this particular wheel, check the validationEngine plugin available at http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/.

You can customize the popup elements as you want, and it is trivial to connect to jQuery.validate.js.

I prefere to change the CSS of bootstrap. Just added the classes of jQuery validate in the right place. field-validation-error and input-validation-error

    form .clearfix.error > label, form .clearfix.error .help-block, form .clearfix.error .help-inline, .field-validation-error {
  color: #b94a48;
}
form .clearfix.error input, form .clearfix.error textarea, .input-validation-error {
  color: #b94a48;
  border-color: #ee5f5b;
}
form .clearfix.error input:focus, form .clearfix.error textarea:focus, .input-validation-error:focus {
  border-color: #e9322d;
  -webkit-box-shadow: 0 0 6px #f8b9b7;
  -moz-box-shadow: 0 0 6px #f8b9b7;
  box-shadow: 0 0 6px #f8b9b7;
}

You can integrate MVC3 validation with Bootstrap framework by adding the following javascript to your page (View)

<script>
$(document).ready(function () {
/* Bootstrap Fix */
$.validator.setDefaults({
    highlight: function (element) {
        $(element).closest("div.control-group").addClass("error");
    },
    unhighlight: function (element) {
        $(element).closest("div.control-group").removeClass("error");
    }
});
var current_div;
$(".editor-label, .editor-field").each(function () {
    var $this = $(this);
    if ($this.hasClass("editor-label")) {
        current_div = $('<div class="control-group"></div>').insertBefore(this);
    }
    current_div.append(this);
});
$(".editor-label").each(function () {
    $(this).contents().unwrap();
});
$(".editor-field").each(function () {
    $(this).addClass("controls");
    $(this).removeClass("editor-field");
});
$("label").each(function () {
    $(this).addClass("control-label");
});
$("span.field-validation-valid, span.field-validation-error").each(function () {
    $(this).addClass("help-inline");
});
$("form").each(function () {
    $(this).addClass("form-horizontal");
    $(this).find("div.control-group").each(function () {
        if ($(this).find("span.field-validation-error").length > 0) {
            $(this).addClass("error");
        }
    });
});
});
</script>

Besides, on the Views (for example "Create.cshtml") make sure that the fields in the form are formatted as the following...

    <div class="editor-label">
        @Html.LabelFor(Function(model) model.Name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(Function(model) model.Name)
        @Html.ValidationMessageFor(Function(model) model.Name)
    </div>

With this solution, it will most likely be enough to just add a javascript without edit the View.

What I've done is taken the css classes for the validation errors and created a new css file with the same classes but with bootstrap values.

You can find it in a nuget package at: http://nuget.org/List/Packages/MahApps.Twitter.Bootstrap

That also provides some scaffolding templates to autocreate new views.

I needed to solve this using Bootstrap 3.1 and Razor. This is what I used:

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

$(function () {

    $('span.field-validation-valid, span.field-validation-error').each(function () {
        $(this).addClass('help-block');
    });

    $('form').submit(function () {
        if ($(this).valid()) {
            $(this).find('div.form-group').each(function () {
                if ($(this).find('span.field-validation-error').length == 0) {
                    $(this).removeClass('has-error');
                }
            });
        }
        else {
            $(this).find('div.form-group').each(function () {
                if ($(this).find('span.field-validation-error').length > 0) {
                    $(this).addClass('has-error');
                }
            });
        }
    });

    $('form').each(function () {
        $(this).find('div.form-group').each(function () {
            if ($(this).find('span.field-validation-error').length > 0) {
                $(this).addClass('has-error');
            }
        });
    });
});

This is a combination of @german's answer and help from this post by "theBraindonor". Updated to use new Bootstrap 3 classes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!