Enable/Disbale Validation in ASP .net MVC 3 - validation

I have a HTML form and within that form I have a DropDownList and a Button that can post to my action method. I want to disable the validation when the post is made by my DropDownList and enable it when it is made by the button.
In my action method I can differentiate, which one is making the post but I can not disable the validation.
I tried to set ValidateRequest = false but it didn't work. I don't want to use Ajax call at this stage.
Thank you

Try this:
Html.DropDownList(..., ..., new { disableValidation = "true" })

Related

.NET MVC unobtrusive validation / checkbox captcha

I'm trying to implement a checkbox captcha I read about here:
http://uxmovement.com/forms/captchas-vs-spambots-why-the-checkbox-captcha-wins/
However I'm having issues adding the checkbox with client side javascript and unobtrusive validation.
I implemented a checkbox with unobtrusive validation based on Darin Dimitrov's answer here: MVC unobtrusive validation on checkbox not working which works perfectly.
However, once I remove the checkbox from my view and add it with this jquery code instead:
jQuery(document).ready(function (jQuery) {
$('div.test').append($("<input>").attr("id", "AcceptsTerms")
.attr("type", "checkbox")
.val("true")
.attr("name", "AcceptsTerms")
.attr("data-val-required", "This field is required.")
.attr("data-val-mustbetrue", "You must accept the terms and conditions")
.attr("data-val", "true")
.addClass("input-validation-error"));
$('div.test').append($('<input>').attr("type", "hidden")
.val("value", "false")
.attr("name", "AcceptsTerms"));
$('div.test').append($("<label>").attr("for", "AcceptsTerms")
.html("Accept terms and conditions"));
$('div.test').append($('<span>').addClass("field-validation-error")
.attr("data-valmsg-replace", "true")
.attr("data-valmsg-for", "AcceptsTerms"));
});
it no longer wants to validate. Are there any known issues with adding form elements after the document has loaded and unobtrusive validation? If so, has any attempted to implement this or have any suggestions on how to go about this?
Looks like I found the solution.
As I suspected and as Sparky mentioned: the jQuery Validate plugin is initialized once on the DOM ready event. Due to this, all I had to do after adding my input dynamically was to reinitialize unobtrusive validation.
I added this first for the rule:
$.validator.unobtrusive.adapters.addBool("mustbetrue", "required");
Then I added this to reinitialize unobtrusive validation:
$("form").removeData('validator');
$("form").removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse($("form"));
Quote OP:
However, once I remove the checkbox from my view and add it with this
jquery code instead: {snip} it no longer wants to validate. Are there
any known issues with adding form elements after the document has
loaded and unobtrusive validation? If so, has any attempted to
implement this or have any suggestions on how to go about this?
This happens because the jQuery Validate plugin is initialized once on the DOM ready event but your checkbox does not yet exist. It's an all-too-common misconception that .validate() is called repeatedly as the user interacts with the form. It is not. .validate() is called once on DOM ready to initialize the plugin and form validation happens automatically when triggered by the default events.
If you need to dynamically alter the form's HTML, you must use one of the plugin's built-in methods to dynamically alter its options.
In your case, you need to use the rules('add') method, sometime after your jQuery adds the checkbox, to alter the rules option to apply your checkbox rule(s).
$(document).ready(function() {
$('div.test').append($("<input>").attr("id", "AcceptsTerms"). ... );
$('#AcceptsTerms').rules('add', {
required: true,
another_rule: parameter,
messages: { // <- this item is optional
required: "custom message"
another_rule: "custom message for this rule"
}
});
...
});

Why unobtrusive validation wont work in asp.net mvc3 without using #Html.BeginForm()

To make unobtrusive validation work in asp.net mvc3 you have to use the html helper #Html.BeginForm() as mentioned in this very good post : http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html.
Without using the helper unobtrusive validation will not be triggered. I could verify that.
Can you explain me what does the helper #Html.BeginForm() do to allow unobtrusive validation to be triggered when the form is submitted ?
Can you also explain me how could I do that manually (read allow unobtrusive validation without calling the #Html.BeginForm()) ?
Please note that I know I can call unobtrusive validation using $("#myform").valid() but I would like to know the magic behind the helper and how to reproduce it.
When you call BeginForm (see http://j.mp/WrmAyk for the FormExtensionsclass), a new MvcForm object is created.
If you look in the constructor of this class (see http://j.mp/Wrml6F for the MvcForm class) you will see that it creates a new FormContext object: _viewContext.FormContext = new FormContext();.
When an input, textarea or select is rendered using the HTML helper, the following is called: tagBuilder.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(name, metadata));, which takes care of rendering the validation attributes from the model metadata.
This GetUnobtrusiveValidationAttributes method (see http://j.mp/Wrn4oa for the HtmlHelper class) checks to see if the FormContext is null before rendering attributes:
FormContext formContext = ViewContext.GetFormContextForClientValidation();
if (formContext == null)
{
return results;
}
This is why no validation attributes are rendered unless you are within a form. You can get round this by creating a 'fake' FormContext, like #karaxuna suggests.
Write this in your view and it will work:
ViewContext.FormContext = ViewContext.FormContext ?? new FormContext();
When code is inside #Html.Beginform (in the same view), then html element validation attributes are got from metadata, In other case, it is not.

MVC3 Force Validation of Hidden Fields

I need to enable the validation of hidden fields using ASP.net MVC3 unobtrusive validation.
The reason behind this is a jquery plugin which hides the original input field to show something fancier. But this disables validation of the field as it becomes hidden.
I tried to use the following code but without success.
$("form").validate({
ignore: ""
});
Thanks
With a hint from this Question I was able to manipulate the options of the unobtrusive validator object.
var validator = $("#myFormId").data('validator');
validator.settings.ignore = "";

How to force form client-side validation in or before $.ajax()

I have a form and unobtrusive validations are enabled. By default in submit method client side validation gets triggered and (if you have any errors) the form looks like this:
The validation happens even before any data gets sent to the server.
Now this behavior doesn't work if you want to use $.ajax method. Client side validation doesn't work. You have to manually check all the fields in your javascript, losing all the beauty of DataAnnotations.
Is there any better solution? I could've use jquery's submit() but I guess it doesn't have callback like $.ajax.
Oh...
if (form.valid()) // do submit
You must force the form to validate before checking if it is valid. Something like this:
var form = $( "#myform" );
form.validate();
if (form.valid()) {
// ...
}
I did...
$("#form-submit-button").click(function (e) {
e.preventDefault(); // Stops the form automatically submitting
if ($("#my-form").valid()) {
$("#my-form").submit();
}
});
This also seems to be a good solution if you have say textboxes with a plugin to make those textboxes into a calendar control. Only reason I say this is because I used Zebra Datepicker with an MVC form and it would submit an invalid form if focus was on the calendar date picker. Using the below code stops this.
I was having the same issue Yablargo was having in that it was saying that valid is not a function, so I came up with this:
For the onclick handler of the submit button, I put this:
onclick="return $(this).closest('form').checkValidity();"

Manually bind JQuery validation after Ajax request

I'm requesting an ASP.net MVC view into a live box and the view contains form fields that have been marked up with attributes to be used by JQuery's unobtrusive validators plug-in.
The client script is not however working and my theory is that its because the validation framework is only being triggered on page load which has long since passed by the time the MVC view has been loaded into the live box.
Thus how can I let the validation framework know that it has new form fields to fix up?
Cheers, Ian.
var $form = $("form");
$form.unbind();
$form.data("validator", null);
$.validator.unobtrusive.parse(document);
// Re add validation with changes
$form.validate($form.data("unobtrusiveValidation").options);
You may take a look at the following blog post. And here's another one.
Another option, rather trick, which worked for me. Just add following line in the beginning of the partial view which is being returned by ajax call
this.ViewContext.FormContext = new FormContext();
Reference
For some reason I had to combine bjan and dfortun's answers...
So I put this in my view:
#{
this.ViewContext.FormContext = new FormContext();
}
And this execute this after the ajax call finishes:
var form = $("#EnrollmentForm");
form.unbind();
form.data("validator", null);
$.validator.unobtrusive.parse(document);
form.validate(form.data("unobtrusiveValidation").options);
I had a similar issue. I had a form that was using Ajax requests to re-display a part of the form with different form fields. I used unobtrusive validation by manually doing it on the client side using the
#Html.TextBoxFor
for my text boxes. For some reason the validation works when attempting to submit with invalid fields (i.e., the text boxes get outlined in red and the appropriate error messages display with the content I put in the
data_val_required
attribute, for example.
However, after I click a button that makes an Ajax request to modify the form with different fields and then submit again, only the red outline on the invalid fields display, but no error messages are rendered.
bjan's trick worked for me, but I still can't see what was causing the issue. All the HTML necessary to carry out the client-side validation was there I just can't figure out why the error message attribute values wouldn't display.
All I can think of is that the jQuery validation code doesn't make a second attempt to check the form fields after a submit was made.

Resources