MVC3 unobtrusive validation group of inputs - asp.net-mvc

I need to validate 3 or more input fields (required at lest one). For example I have Email, Fax, Phone.
I require at least ONE to be filled in. I need both server and client 'unobtrusive validation'. please help. I looked into "Compare" method and tried modifying it but no luck. please help.
thanks

You could write a custom attribute:
public class AtLeastOneRequiredAttribute : ValidationAttribute, IClientValidatable
{
private readonly string[] _properties;
public AtLeastOneRequiredAttribute(params string[] properties)
{
_properties = properties;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (_properties == null || _properties.Length < 1)
{
return null;
}
foreach (var property in _properties)
{
var propertyInfo = validationContext.ObjectType.GetProperty(property);
if (propertyInfo == null)
{
return new ValidationResult(string.Format("unknown property {0}", property));
}
var propertyValue = propertyInfo.GetValue(validationContext.ObjectInstance, null);
if (propertyValue is string && !string.IsNullOrEmpty(propertyValue as string))
{
return null;
}
if (propertyValue != null)
{
return null;
}
}
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = ErrorMessage,
ValidationType = "atleastonerequired"
};
rule.ValidationParameters["properties"] = string.Join(",", _properties);
yield return rule;
}
}
which could be used to decorate one of your view model properties (the one you want to get highlighted if validation fails):
public class MyViewModel
{
[AtLeastOneRequired("Email", "Fax", "Phone", ErrorMessage = "At least Email, Fax or Phone is required")]
public string Email { get; set; }
public string Fax { get; set; }
public string Phone { get; set; }
}
and then a simple controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
Rendering the following view which will take care of defining the custom client side validator adapter:
#model MyViewModel
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script type="text/javascript">
jQuery.validator.unobtrusive.adapters.add(
'atleastonerequired', ['properties'], function (options) {
options.rules['atleastonerequired'] = options.params;
options.messages['atleastonerequired'] = options.message;
}
);
jQuery.validator.addMethod('atleastonerequired', function (value, element, params) {
var properties = params.properties.split(',');
var values = $.map(properties, function (property, index) {
var val = $('#' + property).val();
return val != '' ? val : null;
});
return values.length > 0;
}, '');
</script>
#using (Html.BeginForm())
{
#Html.ValidationSummary(false)
<div>
#Html.LabelFor(x => x.Email)
#Html.EditorFor(x => x.Email)
</div>
<div>
#Html.LabelFor(x => x.Fax)
#Html.EditorFor(x => x.Fax)
</div>
<div>
#Html.LabelFor(x => x.Phone)
#Html.EditorFor(x => x.Phone)
</div>
<input type="submit" value="OK" />
}
Of course the custom adapter and validator rule should be externalized into a separate javascript file to avoid mixing script with markup.

I spent more than 36 hours why the code did not work for me.. At the end , I found out that in my case , I was not supposed to use the property names in this line of code
[AtLeastOneRequired("Email", "Fax", "Phone", ErrorMessage = "At least Email, Fax or Phone is required")]
But I had to use the HTMl element Ids in place of the property names and it worked like magic.
Posting this here if it might help somebody.

Since you are using MVC 3, take a look at great video Brad Wilson had on mvcConf. There's everything you need to create client + server Unobtrusive Validation

#Darin Dimitrov 's solution is probably the standard of creating a custom validation attribute that works with unobtrusive validation. However, using custom validation attributes for unobtrusive validation have some disadvantages such as:
The custom validation attribute is only attached to one properties, so client validation will not work if there's a change event on the other two inputs.
The error message works fine with ValidationSummary, but if you want to display 1 error message for the whole group (which I think is the norm), it would be nearly impossible.
To avoid the first problem, we can add custom validation attribute to each element in the group, which will cause another problem: we have to validate all elements of the group, instead of stopping at the first invalid group element. And of course, the second problem - separate error messages for each element - still remains.
There's another way to handle client side validation of group of inputs, using groups setting in jquery validator (https://jqueryvalidation.org/validate/#groups). The only problem (and a big one) is that unobtrusive validation doesn't support jquery validation's groups by default, so we have to customize a little bit.
Although this answer is hardly "unobtrusive", in my opinion, it is worth trying to get rid of unnecessary complication of code, if your final goal is to validate a group of inputs while using Microsoft's unobtrusive validator library.
First, because groups settings of default jquery validator is not available in jquery unobtrusive validator, we have to override unobtrusive settings (ref. How can I customize the unobtrusive validation in ASP.NET MVC 3 to match my style?)
$("form").on('submit', function () {
var form = this;
var validator = $(this).data("validator");
if (validator.settings && !validator.settings.submitHandler) {
$.extend(true, validator.settings.rules, validationSettings.rules);
$.extend(true, validator.settings.groups, validationSettings.groups);
initGroups(validator);
var fnErrorReplacement = validator.settings.errorPlacement;
validator.settings.errorPlacement = function (error, element) {
validationSettings.errorPlacement(error, element, fnErrorReplacement, form);
}
validator.settings.submitHandler = formSubmitHandler;
}
});
function formSubmitHandler(form) {
form.submit();
}
After that, override unobtrusive validator's groups, rules and errorPlacement settings.
var validationSettings = {
groups: {
checkboxgroup: "Email Fax Phone"
},
rules: {
Email: {
required: function () {
return validateCheckboxGroup(["#Email", "#Fax", "#Phone"]);
}
},
Fax: {
required: function () {
return validateCheckboxGroup(["#Email", "#Fax", "#Phone"]);
}
},
Phone: {
required: function () {
return validateCheckboxGroup(["#Email", "#Fax", "#Phone"]);
}
}
}
,
errorPlacement: function (error, element, fnUnobtrusive, form) {
switch (element.attr("name")) {
case "Email":
case "Fax":
case "Phone":
onGroupError(error, "CheckBoxGroup", form);
break;
default:
fnUnobtrusive(error, element);
break;
}
}
}
function validateCheckboxGroup(names) {
var result = true;
$.each(names, function (index, value) {
if ($(value).is(":checked")) {
result = false;
}
});
return result;
}
Because unobtrusive validator does not implement groups setting of jquery validator, we need to reuse two functions from the two libraries to: (1).split group names (reusing code from jquery validator) and (2) append error element without remove 'input-validation-error' class (reusing function onError from unobtrusive library).
function initGroups(validators) {
validators.groups = {};
$.each(validators.settings.groups,
function (key, value) {
if (typeof value === "string") {
value = value.split(/\s/);
}
$.each(value,
function (index, name) {
validators.groups[name] = key;
});
});
}
function onGroupError(error, inputElementName, form) {
var container = $(form).find("[data-valmsg-for='" + inputElementName + "']"),
replaceAttrValue = container.attr("data-valmsg-replace"),
replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) !== false : null;
container.removeClass("field-validation-valid").addClass("field-validation-error");
error.data("unobtrusiveContainer", container);
if (replace) {
container.empty();
error.appendTo(container);
}
else {
error.hide();
}
}
Finally, use HtmlExtensions.ValidationMessage to create error span of the checkbox group.
#Html.ValidationMessage("CheckBoxGroup", new { #class = "text-danger" })
The keeping of "input-validation-error" class is necessary, so that jquery validator will validate all 3 elements (Email, Phone, Fax) of checkbox group as a whole, instead of validating one by one. The unobtrusive validation library remove this class by default on function onError, so we have to customize this as shown in function onGroupError above.

Related

How to bind posted data named "file[]" to an MVC model?

I am using Redactor as an HTML editor, which has a component for uploading images and files.
Redactor takes care of the client side bit, and I need to provide the server side upload functionality.
I have no problem getting the uploads to work if I use Request.Files in the controller.
But I would like to bind the posted files to a Model, and I seem unable to do this, because the parameter they are sent with is files[] - with square brackets in the name.
My question:
Is it possible to bind the posted "file[]" to an MVC model? It's an invalid property name, and using file alone doesn't work.
This file input looks like this. I can specify a name other than file, but Redactor adds [] to the end, regardless of the name.
<input type="file" name="file" multiple="multiple" style="display: none;">
I am trying to bind to a property like this:
public HttpPostedFileBase[] File { get; set; }
When I watch the upload take place, I see this in the request (I presume that redactor may be adding the square brackets behind the scenes):
Content-Disposition: form-data; name="file[]"; filename="my-image.jpg"
Also relevant:
Redactor always sends the uploading request with content-type as multipart/form-data. So you don't need to add this enctype anywhere
You should create a custom model binder to bind uploaded files to one property.
First create a model with a HttpPostedFileBase[] property
public class RactorModel
{
public HttpPostedFileBase[] Files { get; set; }
}
then implement DefaultModelBinder and override BindProperty
public class RactorModelBinder : DefaultModelBinder
{
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
{
int len = controllerContext.HttpContext.Request.Files.AllKeys.Length;
if (len > 0)
{
if (propertyDescriptor.PropertyType == typeof(HttpPostedFileBase[]))
{
string formName = string.Format("{0}[]", propertyDescriptor.Name);
HttpPostedFileBase[] files = new HttpPostedFileBase[len];
for (int i = 0; i < len; i++)
{
files[i] = controllerContext.HttpContext.Request.Files[i];
}
propertyDescriptor.SetValue(bindingContext.Model, files);
return;
}
}
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
}
Also you should add binder provider to your project, then register it in global.asax
public class RactorModenBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(Type modelType)
{
if (modelType == typeof(RactorModel))
{
return new RactorModelBinder();
}
return null;
}
}
...
ModelBinderProviders.BinderProviders.Insert(0, new RactorModenBinderProvider());
this isn't a general solution, but I guess you get the point.
I encountered similar problem during the integration of jQuery.filer in an ASP.NET MVC project. As jQuery.filer adds "[]" to the end of name attribute of input (i.e. from files to files[]), I had to change the value of name attribute manually as shown below:
$('#FileUpload').attr('name', 'FileUpload');
Here is my approach used in some of project via AJAX and working without any problem. You might give a try and let me know if it works:
ViewModel:
[Display(Name = "Attachments")]
[DataType(DataType.Upload)]
public IEnumerable<HttpPostedFileBase> FileUpload { get; set; }
View:
#model ViewModel
#using (Html.BeginForm("Insert", "Controller", FormMethod.Post,
new { id = "frmCreate", enctype = "multipart/form-data" }))
{
#Html.TextBoxFor(m => m.FileUpload, new { type = "file", multiple = "multiple" })
<button id="btnSubmit" onclick="insert(event)" type="button">Save</button>
}
<script>
function insert(event) {
event.preventDefault();
//As jQuery.filer adds "[]" to the end of name attribute of input (i.e. from files to files[])
//we have to change the value of name attribute manually
$('#FileUpload').attr('name', 'FileUpload');
var formdata = new FormData($('#frmCreate').get(0));
$.ajax({
type: "POST",
url: '#Url.Action("Insert", "Cotroller")',
cache: false,
dataType: "json",
data: formdata,
/* If you are uploading files, then processData and contentType must be set
to falsein order for FormData to work (otherwise comment out both of them) */
processData: false,
contentType: false,
success: function (response, textStatus, XMLHttpRequest) {
//...
}
});
};
$(document).ready(function () {
$('#FileUpload').filer({
//code omitted for brevity
});
});
</script>
Controller:
public JsonResult Insert([Bind(Exclude = null)] ViewModel model)
{
if (ModelState.IsValid)
{
List<FileAttachment> fa = new List<FileAttachment>();
if (model.FileUpload != null)
{
FileAttachment fileAttachment = new FileAttachment //entity model
{
Created = DateTime.Now,
FileMimeType = upload.ContentType,
FileData = new byte[upload.ContentLength],
FileName = upload.FileName,
AuthorId = 1
};
upload.InputStream.Read(fileAttachment.FileData, 0, upload.ContentLength);
fa.Add(fileAttachment);
}
//code omitted for brevity
repository.SaveExperimentWithAttachment(model, fa);
return Json(new { success = true, message = "Record has been created." });
}
// If we got this far, something failed, redisplay form
return Json(new { success = false, message = "Please check the form and try again." });
}

Common validation for multiple inputs MVC 3 [duplicate]

I have a view model that has year/month/day properties for someone's date of birth. All of these fields are required. Right now, if someone doesn't enter anything for the date of birth they get 3 separate error messages.
What I want to do is somehow group those error messages together into 1 message that just says 'Date of birth is required'. So if 1 or more of those fields are blank, they will always just get the 1 validation message.
I NEED this to work on client-side validation via jquery validate and unobtrusive validate. I know this is possible with the jquery validate plugin by looking at this question. But I don't know how to achieve this with asp.net mvc using validation attributes on my model and unobtrusive validation. Hopefully there's some built in way to group properties for validation purposes, but if not can this be done with a custom validation attribute?
Here's what my existing model and view looks like:
The Model:
public class MyModel {
[Required(ErrorMessage = "Year is required")]
public int Year { get; set; }
[Required(ErrorMessage = "Month is required")]
public int Month { get; set; }
[Required(ErrorMessage = "Day is required")]
public int Day { get; set; }
}
The View:
<div>
<label>Date of birth: <span style="color:red;">*</span></label>
<div>#Html.DropDownListFor(m => m.Year, ApplicationModel.GetSelectListForDateRange(DateTime.Today.Year - 16, DateTime.Today.Year - 10), "", new{data_description="birthDate"})#Html.LabelFor(m => m.StudentBirthYear)</div>
<div>#Html.DropDownListFor(m => m.Month, ApplicationModel.GetSelectListForDateRange(1, 12, true), "", new{data_description="birthDate"})#Html.LabelFor(m => m.StudentBirthMonth)</div>
<div>#Html.DropDownListFor(m => m.Day, ApplicationModel.GetSelectListForDateRange(1, 31), "", new{data_description="birthDate"})#Html.LabelFor(m => m.StudentBirthDay)</div>
</div>
<div class="error-container">#Html.ValidationMessageFor(m => m.Year)</div>
<div class="error-container">#Html.ValidationMessageFor(m => m.Month)</div>
<div class="error-container">#Html.ValidationMessageFor(m => m.Day)</div>
I am somewhat late to the party (only couple of years) still...
Most appropriate solution is indeed creating a CustomAttribute but instead of giving you good advice an leaving to die I will show you how.
Custom Attribute:
public class GroupRequiredAttribute : ValidationAttribute, IClientValidatable
{
private readonly string[] _serverSideProperties;
public GroupRequiredAttribute(params string[] serverSideProperties)
{
_serverSideProperties = serverSideProperties;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (_serverSideProperties == null || _serverSideProperties.Length < 1)
{
return null;
}
foreach (var input in _serverSideProperties)
{
var propertyInfo = validationContext.ObjectType.GetProperty(input);
if (propertyInfo == null)
{
return new ValidationResult(string.Format("unknown property {0}", input));
}
var propertyValue = propertyInfo.GetValue(validationContext.ObjectInstance, null);
if (propertyValue is string && !string.IsNullOrEmpty(propertyValue as string))
{
return null;
}
if (propertyValue != null)
{
return null;
}
}
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = ErrorMessage,
ValidationType = "grouprequired"
};
rule.ValidationParameters["grouprequiredinputs"] = string.Join(",", this._serverSideProperties);
yield return rule;
}
}
ViewModel: Decorate only one field on your viewModel like following:
[GroupRequired("Year", "Month", "Day", ErrorMessage = "Please enter your date of birth")]
public int? Year { get; set; }
public int? Month { get; set; }
public int? Day { get; set; }
Jquery: You will need to add adapters in my case it's jquery.validate.unobtrusive.customadapters.js or wherever you register your adapters (you might put this on the page just do it after unobtrusive validation runs).
(function ($) {
jQuery.validator.unobtrusive.adapters.add('grouprequired', ['grouprequiredinputs'], function (options) {
options.rules['grouprequired'] = options.params;
options.messages['grouprequired'] = options.message;
});
}(jQuery));
jQuery.validator.addMethod('grouprequired', function (value, element, params) {
var inputs = params.grouprequiredinputs.split(',');
var values = $.map(inputs, function (input, index) {
var val = $('#' + input).val();
return val != '' ? input : null;
});
return values.length == inputs.length;
});
and that should do it.
For those who are interested what this does: In C# land it grabs the ids of fields glues them with , and puts into custom attribute on Year field.
HTML should look something like this (If it doesn't debug C# attribute):
<input class="tooltip form-control input dob--input-long" data-val="true" data-val-grouprequired="Please enter your date of birth" data-val-grouprequired-grouprequiredinputs="Year,Month,Day" name="Year" placeholder="YYYY" tabindex="" type="text" value="">
Then Jquery validation splits them back into id's and checks if all of them are not empty and that's pretty much it.
You will want to mark fields as invalid somehow (now it would only mark the field attribute is sitting on) most appropriate solution IMHO is to wrap all fields in container with class field-error-wrapper and then add following to your page after Jquery validation is loaded:
$.validator.setDefaults({
highlight: function (element) {
$(element).closest(".field-error-wrapper").addClass("input-validation-error");
},
unhighlight: function (element) {
$(element).closest(".field-error-wrapper").removeClass("input-validation-error");
}
});
instead of marking field it will mark container and then you can write your css in a way that if container is marked with .input-validation-error then all fields inside turn red. I think my job here is done.
EDIT: Ok so there appears to be one more issue where fields get unmarked because validator thinks that day and month are valid and it needs to remove invalid class from parent, validator first marks invalid fields then unmarks valid which causes validation not to get highlighted, so I changed the sequence in which validation happens, I wouldn't recommend overriding this globally (cause I am not sure on what catastrophic side affects it might have) just paste it on the page where you have birthdate fields.
$(function () {
$.data($('form')[0], 'validator').settings.showErrors = function () {
if (this.settings.unhighlight) {
for (var i = 0, elements = this.validElements() ; elements[i]; i++) {
this.settings.unhighlight.call(this, elements[i], this.settings.errorClass, this.settings.validClass);
}
}
this.hideErrors();
for (var i = 0; this.errorList[i]; i++) {
var error = this.errorList[i];
this.settings.highlight && this.settings.highlight.call(this, error.element, this.settings.errorClass, this.settings.validClass);
this.showLabel(error.element, error.message);
}
if (this.errorList.length) {
this.toShow = this.toShow.add(this.containers);
}
if (this.settings.success) {
for (var i = 0; this.successList[i]; i++) {
this.showLabel(this.successList[i]);
}
}
this.toHide = this.toHide.not(this.toShow);
this.addWrapper(this.toShow).show();
};
});
Hope this saves you some time.
You could do that simply using CustomAttribute.
Just put this attribute on your model
[CustomValidation(typeof(MyModel), "ValidateRelatedObject")]
and then simply define the rules to validate the values in the following method:
public static ValidationResult ValidateRelatedObject(object value, ValidationContext context)
{
var context = new ValidationContext(value, validationContext.ServiceContainer, validationContext.Items);
var results = new List<ValidationResult>();
Validator.TryValidateObject(value, context, results);
// TODO: Wrap or parse multiple ValidationResult's into one ValidationResult
return result;
}
For more information, you could visit this link.
You should implement IValidatableObject and take of the Require. Then the validation on the server side will do the job, something like:
public class MyModel : IValidatableObject
{
public int Year { get; set; }
public int Month { get; set; }
public int Day { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (/*Validate properties here*/) yield return new ValidationResult("Invalid Date!", new[] { "valideDate" });
}
}
For client side validation you need to implement your own function, and prompt the error to the user somehow.
EDIT: Given that you still need client side validation, you should do something like this:
$("form").validate({
rules: {
Day: { required: true },
Month : { required: true },
Year : { required: true }
},
groups: {
Date: "Day Month Year"
},
errorPlacement: function(error, element) {
if (element.attr("id") == "Day" || element.attr("id") == "Month" || element.attr("id") == "Year")
error.insertAfter("#Day");
else
error.insertAfter(element);
}
});
Hi I hope this fulfill your requirement
//--------------------------HTML Code-----------------------------
<form id="myform">
<select name="day">
<option value="">select</option>
<option value="1">1</option>
<select>
<select name="mnth">
<option value="">select</option>
<option value="Jan">Jan</option>
<select>
<select name="yr">
<option value="">select</option>
<option value="2015">2015</option>
<select>
<br/>
<input type="submit" />
<br/>
<div id="msg"></div>
</form>
//-------------------------------JS Code to validate-------------
$(document).ready(function() {
$('#myform').validate({
rules: {
day: {
required: true
},
mnth: {
required: true
},
yr: {
required: true
}
},
errorPlacement: function (error, element) {
var name = $(element).attr("name");
error.appendTo($("#msg"));
},
messages: {
day: {
required: "Date of birth is required"
},
mnth: {
required: "Date of birth is required"
},
yr: {
required: "Date of birth is required"
}
},
groups: {
p: "day mnth yr"
},
submitHandler: function(form) { // for demo
alert('valid form');
return false;
}
});
});
Here is Running Example

MVC Custom Validation for List on Client Side

I'm trying to write a custom validator that works on the client side that validates that all checkboxes have been ticked.
Here's the declaration on the model:
[DeclarationsAccepted(ErrorMessage = "You must tick all declarations")]
public IList<DeclarationQuestion> DeclarationQuestions { get; set; }
And here's the attribute:
public class DeclarationsAccepted : ValidationAttribute, IClientValidatable
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var questions = value as IList<DeclarationQuestion>;
if (questions != null && questions.All(c => c.Answer))
{
return ValidationResult.Success;
}
return new ValidationResult("You must accepted all declarations to continue");
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var modelClientValidationRule = new ModelClientValidationRule
{
ValidationType = "declarationsaccepted",
ErrorMessage = FormatErrorMessage(metadata.DisplayName)
};
yield return modelClientValidationRule;
}
}
So far so good, works server side.
For the client I'm wiring this up as follows:
jQuery.validator.addMethod('declarationsaccepted', function (value, element, params) {
//Implement logic here to check all boxes are ticked
console.log(value);
return false;
}, '');
jQuery.validator.unobtrusive.adapters.add('declarationsaccepted', {}, function (options) {
options.rules['declarationsaccepted'] = true;
options.messages['declarationsaccepted'] = options.message;
});
I'm displaying the checkboxes like this:
#{ var questionIndex = 0; }
#foreach (var question in Model.DeclarationQuestions)
{
#Html.CheckBoxFor(model => Model.DeclarationQuestions[questionIndex].Answer, new { id = "DeclarationQuestions" + questionIndex})
questionIndex++;
}
And then displaying the validation message using this:
#Html.ValidationMessageFor(c => c.DeclarationQuestions)
When I submit the form the message is displayed but only after a post back to the server. Is there any way to get this to work on the client side?
The reason you will not get client side validation is because the html helpers generate data-val-* attributes for controls associated with properties. jquery.validate.unobtrusive reads those attributes when the form is parsed and using rules, displays an error message in the appropriate element generated by ValidationMessageFor() associated with that control (it does this by matching up the id attributes of the elements - the error message is generated in a span with <span for="TheIdOfTheAssociatedControl" ...>).
You don't (and cant) generate a control for property DeclarationQuestions (only for properties of each item in DeclarationQuestions so there is nothing that can be matched up.
You could handle this by including your own error message placeholder and intercepting the .submit event
html (add css to style #conditions-error as display:none;)
<span id="delarations-error" class="field-validation-error">
<span>You must accept all declarations to continue.</span>
</span>
Script
var declarationsError = $('#delarations-error');
$('form').submit(function() {
var isValid = $('.yourCheckBoxClass').not(':checked') == 0;
if(!isValid) {
declarationsError.show(); // display error message
return false; // prevent submit
}
});
$('.yourCheckBoxClass').change(function() {
if($(this).is(':checked')) {
declarationsError.hide(); // hide error message
}
});
Side note: You loop for generating the checkboxes should be
for (int i = 0; i < Model.DeclarationQuestions.Count; i++)
{
#Html.CheckBoxFor(m => m.DeclarationQuestions[i].Answer, new { id = "DeclarationQuestions" + i})
}

Seeking a reusable PostalCode model for MVC

I have the following validation/presentation that I use on a postal code field, in a ViewModel, in my ASP.NET MVC web site. I'd like to share this implementation with 5 other postal code editors, on other models, in my application. How can I avoid duplicating this code?
[Required]
[RegularExpression(LocationMatch.NorthAmericanPostalCodePattern,
ErrorMessage = "You may look up cities here, but must submit a North American postal code")]
[Display(Name = "Postal Code", Prompt = "or type city")]
[Remote("ValidatePostalCode", "Utilities")]
[CustomValidation(typeof(CandidateMobileEditor), "ValidatePostalCode")]
public string PostalCode { get; set; }
public static ValidationResult ValidatePostalCode(string postalCode) {
return LocationMatch.Closest(postalCode) == null ?
new ValidationResult("Postal code not found") : null;
}
public void Load(Candidate sourceProfile) {
PrimaryPostalCode = sourceProfile.Account.FormattedPostalCode;
}
public void Save(Candidate targetProfile) {
targetProfile.Account.FormattedPostalCode = LocationMatch.Closest(PrimaryPostalCode).PostalCode;
}
Additionally, I have the following JavaScript associated with each postal code field. I mention this for completeness, as I am aware of some ways to trigger this to be activated from common code, but only if I can cause a common template to load or decorate the model with some common custom attributes.
singletons.lac = new locationAutocomplete("input[name='PrimaryPostalCode']");
function locationAutocomplete(selector) {
var cache = {}, lastXhr;
var locationField = $(selector);
locationField.autocomplete({
minLength: 5,
delay: 0, // note the lookup delay is increased during the first search event
search: function (event, ui) { locationField.autocomplete("option", "delay", 300); },
change: function (event, ui) { locationField.change(); },
source: function (request, response) {
var term = request.term;
if (term in cache) {
response(cache[term]);
return;
}
lastXhr = $.getJSON(SiteContext.VirtualRoot + "Utilities/GetMatchingLocations", request, function (data, status, xhr) {
cache[term] = data;
if (xhr === lastXhr) {
response(data);
}
});
}
});
}
Create a new ViewModel specifically for this postal code editor, then create a partial view to hold the required html and javascript.
when you need to use this you can include this ViewModel in your page ViewModel and use #Html.Partial("Your Postal Partial View File") to load this into your page.

How can I ignore case in a RegularExpression?

I have an asp.net MVC application. There is an entity called File that it has a property called Name.
using System.ComponentModel.DataAnnotations;
public class File {
...
[RegularExpression(#"([^.]+[.](jpg|jpeg|gif|png|wpf|doc|docx|xls|xlsx ..., ErrorMessage = "Invali File Name"]
public string Name{ get; set; }
...
}
There is a RegularExpressionValidator that checks file extensions.
Is there a quick way I can tell it to ignore the case of the extension without having to explicitly add the upper case variants to my validation expression?
I need this RegularExpressionValidator for both Server-side and client-side.
"(?i)" can be used for Server-side, but this doesn't work client-side
One way I can think of is writing a custom validation attribute:
public class IgnorecaseRegularExpressionAttribute : RegularExpressionAttribute, IClientValidatable
{
public IgnorecaseRegularExpressionAttribute(string pattern): base("(?i)" + pattern)
{ }
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ValidationType = "icregex",
ErrorMessage = ErrorMessage
};
// Remove the (?i) that we added in the pattern as this
// is not necessary for the client validation
rule.ValidationParameters.Add("pattern", Pattern.Substring(4));
yield return rule;
}
}
and then decorate your model with it:
[IgnorecaseRegularExpression(#"([^.]+[.](jpg|jpeg|gif|png|wpf|doc|docx|xls|xlsx", ErrorMessage = "Invalid File Name"]
public string Name { get; set; }
Finally write an adapter on the client:
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script type="text/javascript">
jQuery.validator.unobtrusive.adapters.add('icregex', [ 'pattern' ], function (options) {
options.rules['icregex'] = options.params;
options.messages['icregex'] = options.message;
});
jQuery.validator.addMethod('icregex', function (value, element, params) {
var match;
if (this.optional(element)) {
return true;
}
match = new RegExp(params.pattern, 'i').exec(value);
return (match && (match.index === 0) && (match[0].length === value.length));
}, '');
</script>
#using (Html.BeginForm())
{
#Html.EditorFor(x => x.Name)
#Html.ValidationMessageFor(x => x.Name)
<input type="submit" value="OK" />
}
Of course you could externalize the client rules into a separate javascript file so that you don't have to repeat it everywhere.
Umh could you show the Client Validation?
umh I think that you can create your own Attribute that derives from RegularExpression and add the functionallity to ignore case.

Resources