New2Development
New2Development

Reputation: 41

ASP.NET MVC3 JQuery Validate Plugin custom error Placement

I am trying to handle errorPlacement JQuery Validate plugin in ASP.NET MVC 3 Project with Unobtrusive validation provided by Microsoft. I am never able to hit the errorPlacement function and I am not sure what am I doing wrong. I am providing the code for Model/View/Controller below. Please let me know what am I doing wrong?

View


<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<Project.Models.SampleModel>" %>
<!DOCTYPE html>
<html>
<head runat="server">
    <title>Index</title>
</head>
<body>
    <script src="<%: Url.Content("~/Scripts/jquery-1.4.4.min.js") %>" type="text/javascript"></script>
    <script src="<%: Url.Content("~/Scripts/jquery.validate.js") %>" type="text/javascript"></script>
    <script src="<%: Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js") %>" type="text/javascript"></script>
    <script type="text/javascript">

         $(document).ready(function ()
    {
        $("#form").validate(
      {
          errorPlacement: function (error, element)
          {
              alert("Code to define customer error");
          }
      })

    });
    </script>
    <% using (Html.BeginForm("Index", "Sample", FormMethod.Post, new { id = "form" }))
       { %>
    <%: Html.ValidationSummary(false) %>
    <fieldset>
        <legend>NewModel</legend>
        <div class="editor-label">
            <%: Html.LabelFor(model => model.Name) %>
        </div>
        <div class="editor-field">
            <%: Html.EditorFor(model => model.Name) %>
        </div>
        <div class="editor-label">
            <%: Html.LabelFor(model => model.Age) %>
        </div>
        <div class="editor-field">
            <%: Html.EditorFor(model => model.Age) %>
        </div>
        <div class="editor-label">
            <%: Html.LabelFor(model => model.Address) %>
        </div>
        <div class="editor-field">
            <%: Html.EditorFor(model => model.Address) %>
        </div>
        <br />
        <p>
            <input type="submit" id="submit" value="Submit" />
        </p>
    </fieldset>
    <% } %>
</body>
</html>




Model


public class SampleModel
    {


        [Required]
        [DataType(DataType.Text)]
        [DisplayName("Name")]
        public string Name { get; set; }

        [Required]
        [DataType(DataType.Text)]
        [DisplayName("Age")]
        public string Age { get; set; }

        [Required]
        [DataType(DataType.MultilineText)]
        [DisplayName("Address")]
        public string Address { get; set; }


    }


Controller

public class SampleController : Controller
    {
        //
        // GET: /New/

        public ActionResult Index()
        {
            return View();
        }

    }

Upvotes: 4

Views: 6915

Answers (7)

NickWebman
NickWebman

Reputation: 188

Your custom code and options need to load AFTER jquery.validate and BEFORE jquery.validate.unobtrusive.

Upvotes: 0

Amila
Amila

Reputation: 3816

After reading through many posts and trying to find an answer I wasn't able to get error placement to work. I use twitter bootstrap in my MVC 4 application and wanted a way to put the error class in to the control-group div to make it go red when there is an error.

It wasn't possible to access the initialized jquery validator object through the form.

As a fact, we know that we can pass settings to jQuery validation when initializing validation in a website. But in MVC, it is done automatically (I'm not sure In Where it is done)

Anyway, If we find this initialized object, we can extend the settings and pass our own functions to highlight, unhighlight, showErrors, etc.

How to do this

jQuery.validator provided the instance of validation object that was already initialized. in that object, there is a function called setDefaults. you can create a settings object with the functions that you want to customize. Example below

$(function () {
        var settings = {
            highlight: function (element, errorClass, validClass) {
                $(element).parents('.control-group').addClass('error');
            },
            unhighlight: function (element, errorClass, validClass) {
                $(element).parents('.control-group').removeClass('error');
            }
        }

        if (jQuery.validator) {
            jQuery.validator.setDefaults(settings);
        }
});

Upvotes: 0

Lykers
Lykers

Reputation: 1

Try to replace with jquery.unobtrusive-ajax.min.js.

It worked for me but I didn't know what errors could possibly occur in future.

Upvotes: 0

achekh
achekh

Reputation: 1106

I found an article here which addresses the issue.

In short:

var valOpts = $.data($('form')[0], 'validator').settings; //we've got jQuery.validation settings woohoo!
var baseError = valOpts.errorPlacement;
valOpts.errorPlacement = function (error, input) {
    input.attr('title', error.text()); //error is the $('<span>...</span>')
    baseError(error, input); //removing this breaks form validation
};

Upvotes: 5

AJC
AJC

Reputation: 1893

while having a similar problem I found a solution. Here is my solution. I link to my question and copy the answer below. Hope this is what you are looking for:

Integrating qTip with MVC3 and jQuery Validation (errorPlacement)

1) First, locate the script jquery.validate.unobtrusive.js provided by microsoft.

2) Second, on the script locate the function validationInfo(form) and replace the errorPlacement instruction in the options structure with the one provided by qTip, or any of your choice.

3) Same goes for style and other options you wish to change in how validation is handled.

4) Include all necessary files were needed.

Hope this helps someone having a similar problem.

Example Code:

function validationInfo(form) {
    var $form = $(form),
        result = $form.data(data_validation);

    if (!result) {
        result = {
            options: {  // options structure passed to jQuery Validate's validate() method
                //errorClass: "input-validation-error",
                errorClass: "error",
                errorElement: "span",
                //errorPlacement: $.proxy(onError, form),
                errorPlacement: function (onError, form) {
                    var error = onError;
                    var element = form;
                    // Set positioning based on the elements position in the form
                    var elem = $(element),
                        corners = ['left center', 'right center'],
                        flipIt = elem.parents('span.right').length > 0;

                    // Check we have a valid error message
                    if (!error.is(':empty')) {
                        // Apply the tooltip only if it isn't valid
                        elem.filter(':not(.valid)').qtip({
                            overwrite: false,
                            content: error,
                            position: {
                                my: corners[flipIt ? 0 : 1],
                                at: corners[flipIt ? 1 : 0],
                                viewport: $(window)
                            },
                            show: {
                                event: false,
                                ready: true
                            },
                            hide: false,
                            style: {
                                classes: 'ui-tooltip-red' // Make it red... the classic error colour!
                            }
                        })

                        // If we have a tooltip on this element already, just update its content
                        .qtip('option', 'content.text', error);
                    }

                    // If the error is empty, remove the qTip
                    else { elem.qtip('destroy'); }
                },
                invalidHandler: $.proxy(onErrors, form),
                messages: {},
                rules: {},
                success: $.proxy(onSuccess, form)
            },
            attachValidation: function () {
                $form.validate(this.options);
            },
            validate: function () {  // a validation function that is called by unobtrusive Ajax
                $form.validate();
                return $form.valid();
            }
        };
        $form.data(data_validation, result);
    }

    return result;
}

Upvotes: 0

ckaut
ckaut

Reputation: 21

In MVC3 Microsoft uses jQuery validation plugin for builtin validation. The usage is in jquery.validate.unobtrusive.min.js. Find OnError there - and change it's logic.

function onError(error, inputElement) {  // 'this' is the form element
        var container = $(this).find("[data-valmsg-for='" + inputElement[0].name + "']"),
            replace = $.parseJSON(container.attr("data-valmsg-replace")) !== false;

        container.removeClass("field-validation-valid").addClass("field-validation-error");
        error.data("unobtrusiveContainer", container);

        if (replace) {
            container.empty();
            error.removeClass("input-validation-error").appendTo(container);
        }
        else {
            error.hide();
        }
    }

Upvotes: 2

mrtsherman
mrtsherman

Reputation: 39872

Looks like your code may have gotten mangled a little bit in posting, but I will try. Your jQuery code looks good to me.

You included the jquery and jquery validator libaries? You are running your code inside $(document).ready? You have a field that is invalid? Your alert will only call if there is an error. You can trigger by hitting submit with an invalid field.

Upvotes: 0

Related Questions