ASP.NET MVC3 jQuery Validate Plugin custom error Location

I am trying to process the errorPlacement jQuery Validate plugin in an ASP.NET MVC 3 project with unobtrusive validation provided by Microsoft. I can never get into the errorPlacement function, and I'm not sure what I'm doing wrong. Below is the code for Model / View / Controller. Please let me know what I am 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(); } } 
+4
source share
7 answers

I found an article here that 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 }; 
+5
source

In MVC3, Microsoft uses the jQuery validation plugin for inline validation. Used in jquery.validate.unobtrusive.min.js. Find OnError there - and change its 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(); } } 
+2
source

It looks like your code may be a bit crippled in the publication, but I will try. Your jQuery code looks good to me.

Have you included the jquery and jquery validator libraries? Are you running your code inside $ (document) .ready? Do you have a field that is invalid? Your notification will be triggered only when an error occurs. You can invoke by clicking submit with an invalid field.

0
source

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

QTip integration with MVC3 and jQuery check (errorPlacement)

1) First find the jquery.validate.unobtrusive.js script provided by Microsoft.

2) Secondly, on the script, find the function validationInfo (form) function and replace the errorPlacement command in the options structure with the one provided by qTip, or any of your wishes.

3) The same goes for the style and other parameters that you want to change in how validation is handled.

4) You must include all the necessary files.

Hope this helps someone who has a similar issue.

Code example:

 function validationInfo(form) { var $form = $(form), result = $form.data(data_validation); if (!result) { result = { options: { // options structure passed to jQuery Validate 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; } 
0
source

Try replacing with jquery.unobtrusive-ajax.min.js .

This worked for me, but I did not know what errors might happen in the future.

0
source

After reading a lot of posts and trying to find the answer, I could not get the error placement to work. I use twitter bootstrap in my MVC 4 application and wanted to put the error class in the div control group so that it lights up when there is an error.

Failed to access initialized jquery validation object via form.

As a fact, we know that we can pass the settings for jQuery validation when initializing validation on the website. But in MVC, this is done automatically (I'm not sure where this is done)

In any case, if we find this initialized object, we can expand the settings and pass our own functions to highlight, not highlight, showErrors, etc.

How to do it

jQuery.validator provided an instance of a validation object that has already been initialized. there is a setDefaults function in this object. You can create a settings object with the features 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); } }); 
0
source

Custom code and parameters should load AFTER jquery.validate and BEFORE jquery.validate.unobtrusive.

0
source

Source: https://habr.com/ru/post/1340045/


All Articles