ASP.NET MVC Validation add class to containing div - asp.net-mvc

I'm using bootstrap CSS form styles, When a textbox gets a validation error message, I need to put the class "error" on the containg . How can I do this?
Problem is, all the validations fire on ajax before submitting the form, except for my custom validators which only fire on post. So need to make sure it happens 4 both scenarios.
http://twitter.github.com/bootstrap/base-css.html#forms

Inside the onError function in jquery.validate.unobtrusive, just add the .addClass("error") line like this:
function onError(error, inputElement) { // 'this' is the form element
var container = $(this).find("[data-valmsg-for='" + escapeAttributeValue(inputElement[0].name) + "']"),
replace = $.parseJSON(container.attr("data-valmsg-replace")) !== false;
container.removeClass("field-validation-valid").addClass("field-validation-error");
error.data("unobtrusiveContainer", container);
container.parents(".field-encapsulator:first").addClass("error");
if (replace) {
container.empty();
error.removeClass("input-validation-error").appendTo(container);
}
else {
error.hide();
}
}

ASP.NET MVC adds the field-validation-error class to the error message element, and input-validation-error to form controls, both on the server-side and client-side via javascript. There's no containing element, depending on your code the form control and its label may or may not be under the same containing element. And, even if they do, MVC will set the mentioned classes to the form control and error message element and not the containing element.
Also, when you autogenerate a form using Html.EditorForModel() the generated markup is like this:
<div class="editor-label"><label for="foo">Foo</label></div>
<div class="editor-field"><input name="foo"/></div>
There's no containing element that could map to the control-group class on Twitter Bootstrap. You could change this template by adding an EditorTemplates/Object.cshtml template.
I'd suggest you adapt Twitter Bootstrap to ASP.NET MVC and not the other way around.

As described in some of the answers at How to add a 'submitHandler' function when using jQuery Unobtrusive Validation?, the settings can be accessed by $("form").data("validator").settings.
And you can then set any valid/invalid class you like:
var settings = $("form").data("validator").settings;
settings.errorClass += " is-invalid";
settings.validClass += " is-valid";

Related

What is the reson behind using $("form").removeData("validator") & $("form").removeData("unobtrusiveValidation"); inside partial view

I am reading the following example link about displaying a partial view inside a popup menu. but i have noticed that inside the partial view the author uses the following code at the end of the view:-
$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");
so can anyone advice what is the purpose behind adding this code?
It removes the jQuery validation from the form. Here is a reference to the validation data.
var form = $(formSelector)
.removeData("validator") /* added by the raw jquery.validate plugin */
.removeData("unobtrusiveValidation");
/* added by the jquery unobtrusive plugin */
To be specific to the implementation in partial view, you can implement the validation with a method like this
function ApplyValidation() {
$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");
}
In unobtrusive validation, once the validators have been applied for a document, any other validators of dynamic content(partial views or jquery induced html controls) will not be applied. Once we reload the validators, it will bind rules defined inside the model with rules implementation provided by JQuery library, so validation will be performed seamlessly.
The other option (instead of reloading validators) you have is to inject the new rules as shown here.
Access the form's unobtrusiveValidation data using the jquery data method ($(form).data('unobtrusiveValidation')) and access the rules collection and add the new elements attributes.
In my case I use $("form").removeData("validator") because I have 2 differents validations for the same form.. calling different validation according the button has pressed ;)

DriverResult Editor render custom template in Orchard

I'm working over this module (Extended Registration). This module provides a simple way of showing custom user fields in the registration.
Overrides the AccountController form user and loads the Editor Template in the Registration template
AccountController
var shape = _orchardServices.New.Register();
var user = _orchardServices.ContentManager.New("User");
if (user != null) {
shape.UserProfile= _contentManager.BuildEditor(user);
}
return new ShapeResult(this, shape);
Register.cshtml
</div>
#if (Model.OERegister != null) {
<fieldset>
#Display(Model.UserProfile)
</fieldset>
}
<div>
The shape here is the Editor Template (EditorTemplate/Parts/template)
It Works just fine, but I need to hide some fields from the registration form.
I'm kind of lost here, and I want to do it in the most Orchish way.
Thanks in advance.
As far as I understand the question here is how to generally hide some fields from a form.
Depending on how the author of the form's code designed it or whether you're the developer, there are multiple ways:
Have parts of the form in separate shapes, and return their factories in a Combined driver result from a driver. This means, your driver building part of the form by providing the shapes for a part's editor will register multiple shapes (this is similar to what e.g. BodyPartDriver.Display() does: it returns three separate shape registrations). Now these can be individually controlled by placement, so you can also hide them.
If you have no such fine control over how the form is built, you can still override the shape templates containing the fields you want to hide. Then in the override you can freely customize the look of the form. Beware that unlike the first solution, this won't automatically prevent the user from posting the hidden fields' data to the server, and thus saving it.
BTW I don't think the ContentManager.New() can ever return null. Even if the content type is not statically defined (i.e. created from a migration or through ContentDefinitionManager) it will return a content item.

ASP.NET MVC Unobtrusive validation - why form context is needed?

I'm trying to enable unobtrusive javascript validation for dynamically created items. The problem with javascript was already solved in another SO question and this is not the case here.
Dynamic creation of items in this case is just cloning of one empty item that is generated outside of the main form.
The problem is that if I use html helpers like TextBoxFor, CheckBoxFor, ... outside the html form element then attributes required in order for the validation to work (eg. data-val-required) are not generated.
I've already checked the MVC source code and there is a line that returns empty attribute list if FormContext is null. (this throws no exceptions)
Why?
You could manually fake a form context. For example if you had some partial view which doesn't contain a <form> element and which is called using AJAX to regenerate some input elements you could do this:
#model MyViewModel
#{
ViewContext.FormContext = new FormContext();
}
#Html.LabelFor(x => x.Foo)
#Html.EditorFor(x => x.Foo)
#Html.ValidationMessageFor(x => x.Foo)
The corresponding input elements will now posses the data-* attributes. But that might not be enough. If you are only refreshing (using AJAX) only a portion of the <form> but not actually replacing the form element in the DOM calling $.validator.unobtrusive.parse wouldn't suffice. You need to remove any previous validations associated to this element:
success: function(result) {
// we are replacing only a portion of the form
$('#somePartOfTheForm').html(result);
$('form').removeData('validator');
$('form').removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse('form');
}

Getting client side validation to work with Telerik MVC Window

I am using a telerik mvc window extension that is triggered from a custom template link in a telerik mvc grid. The window is modal and it contains a form for editing data. After successfully implementing client side validation using a standard html page, I have been trying to implement it in the telerik mvc window. I have not been able to do so successfully. Is this possible? Does anybody have a working example of this?
Thanks
Ozzy
You need to load to page in an IFrame. To do this, make sure the url in LoadContentFrom method starts with http or https:
<%= Html.Telerik().Window()
.Name("Window")
.LoadContentFrom("http://www.example.com")
%>
if you're using the Url.Action() helper to get the url, include the protocol parameter to get the full url.
E.g
Url.Action("action name","controler name", "http") <--may also need to include route values or null route value dictionary.
To close to window, you'll need to make a call back to the parent view, try this:
add a bool isValid property to your model
if succesfully validated, reload the view with isValid equals true
onload:
var isValid = '<%: Model.IsValid%>';
if(isValid == 'True')
{
window.parent.$('#MyWindow').data('tWindow').close();
}
It is possible. First make sure you have your ViewModel property that needs validation decorated with the appropriate attribute. Eg: [Required(ErrorMessage = "this is required")]
Then include all the client validation scripts found in telerik's folder in your application.
<script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
Make sure you use the latest build of teleriks extensions. hth.

Required Attribute for bool value type when used as checkbox

I'm running into a problem where I have a simple add/edit form and using client-side validation (jQuery/MicrosoftMvcJQueryValidation.js) which is generated from data annotations and enabled client side by calling the following in my view:
<% Html.EnableClientValidation(); %>
This seems to work fine for most elements, however I have an instance where I have a boolean property which is rendered as a checkbox using:
<%= Html.EditorFor(model => model.Chargeable)%>
Which can be either true/false (ticked/unticked).
As the bool is a value type, and not nullable, it is being rendered as a required property and displays an error (client side) when the form is submitted reading "The Chargeable field is required.", however, as the HTML that is generated is two part (both checkbox and hidden value) it will pass the post back validation.
After browsing the MVC 2 source code, I've managed to put a "quick and dirty" fix in for the moment, which is to set:
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
Any one else got any ideas or suggestions on how I can get around this?
IMO, I dont think MVC should be setting the client-side required validator for checkboxes rendered using the Html.EditorFor/Html.CheckBox(For) methods.
Note: I'm using the ASP.NET MVC 2 RC2 and the MicrosoftMvcJQueryValidation.js from the matching MVC Futures release.
I suppose the easiest way of handling it is to call the rules("remove", [rules]) function on the elements (mainly checkboxes) that I want to remove the client-side validation from:
<script type="text/javascript">
$(document).ready(function() {
$('#Chargeable').rules('remove', 'required');
});
</script>

Resources