Common validation for multiple inputs MVC 3 [duplicate] - asp.net-mvc

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

Related

asp.net/MVC custom model validation attribute not working

(I've made some progress, but still not working, updates below...)
I am trying to implement ye olde start date is not greater than end date validation. This is the first time I've attempted to write a custom validation attribute. Based on what I've been reading out here, this is what I've come up with...
custom validation attribute:
public class DateGreaterThanAttribute : ValidationAttribute
{
private string _startDatePropertyName;
public DateGreaterThanAttribute(string startDatePropertyName)
{
_startDatePropertyName = startDatePropertyName;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var propertyInfo = validationContext.ObjectType.GetProperty(_startDatePropertyName);
if (propertyInfo == null)
{
return new ValidationResult(string.Format("Unknown property {0}", _startDatePropertyName));
}
var propertyValue = propertyInfo.GetValue(validationContext.ObjectInstance, null);
if ((DateTime)value > (DateTime)propertyValue)
{
return ValidationResult.Success;
}
else
{
var startDateDisplayName = propertyInfo
.GetCustomAttributes(typeof(DisplayNameAttribute), true)
.Cast<DisplayNameAttribute>()
.Single()
.DisplayName;
return new ValidationResult(validationContext.DisplayName + " must be later than " + startDateDisplayName + ".");
}
}
}
view model:
public class AddTranscriptViewModel : IValidatableObject
{
...
[DisplayName("Class Start"), Required]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
[RegularExpression(#"^(1[012]|0?[1-9])[/]([12][0-9]|3[01]|0?[1-9])[/](19|20)\d\d.*", ErrorMessage = "Date out of range.")]
public DateTime? ClassStart { get; set; }
[DisplayName("Class End"), Required]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
[RegularExpression(#"^(1[012]|0?[1-9])[/]([12][0-9]|3[01]|0?[1-9])[/](19|20)\d\d.*", ErrorMessage = "Date out of range.")]
[DateGreaterThan("ClassStart")]
public DateTime? ClassEnd { get; set; }
...
}
Relevant portions of the front-end:
#using (Html.BeginForm("AddManualTranscript", "StudentManagement", FormMethod.Post, new { id = "studentManagementForm", #class = "container form-horizontal" }))
{
...
<div class="col-md-4" id="divUpdateStudent">#Html.Button("Save Transcript Information", "verify()", false, "button")</div>
...
<div class="col-md-2">
<div id="divClassStart">
<div>#Html.LabelFor(d => d.ClassStart, new { #class = "control-label" })</div>
<div>#Html.EditorFor(d => d.ClassStart, new { #class = "form-control" }) </div>
<div>#Html.ValidationMessageFor(d => d.ClassStart)</div>
</div>
</div>
<div class="col-md-2">
<div id="divClassEnd">
<div>#Html.LabelFor(d => d.ClassEnd, new { #class = "control-label" })</div>
<div>#Html.EditorFor(d => d.ClassEnd, new { #class = "form-control" }) </div>
<div>#Html.ValidationMessageFor(d => d.ClassEnd)</div>
</div>
</div>
...
}
<script type="text/javascript">
...
function verify() {
if ($("#StudentGrades").data("tGrid").total == 0) {
alert("Please enter at least one Functional Area for the transcript grades.");
}
else {
$('#studentManagementForm').trigger(jQuery.Event("submit"));
}
}
...
</script>
The behavior I'm seeing is that all other validations on all other fields on the form, which are all standard validations like Required, StringLength, and RegularExpression, etc., are working as expected: when I click the "save" button, the red text appears for those fields that don't pass. I have put a breakpoint in my IsValid code, and it doesn't hit unless all the other validations are passed. And even then, if the validation check fails, it doesn't stop the post.
Further reading led me to add the following to Global.asax.cs:
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(DateGreaterThanAttribute), typeof(DataAnnotationsModelValidator));
But that made no difference. I also tested ModelState.IsValid in the postback function, and it was false. But for the other validators if never gets that far. I even noticed in the markup that it seems like a lot of markup gets created on those fields that have validation attributes when the page is generated. Where does that magic occur and why is my custom validator out of the loop?
There's a lot of variation out there, but what I have here seems to generally line up with what I'm seeing. I've also read some about registering validators on the client side, but that seems to only apply to client-side validation, not model validation at submit/post. I won't be embarrassed if the answer is some silly oversight on my part. After about a day on this, I simply need it to work.
Update:
Rob's answer led me to the link referenced in my comment below, which then led me here client-side validation in custom validation attribute - asp.net mvc 4 which led me here https://thewayofcode.wordpress.com/tag/custom-unobtrusive-validation/
What I read there jived with what I had observed, that something was missing in the markup, and it looked like the author outlined how to get it in there. So I added the following to my validation attribute class:
public class DateGreaterThanAttribute : ValidationAttribute, IClientValidatable // IClientValidatable added here
...
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
//string errorMessage = this.FormatErrorMessage(metadata.DisplayName);
string errorMessage = ErrorMessageString;
// The value we set here are needed by the jQuery adapter
ModelClientValidationRule dateGreaterThanRule = new ModelClientValidationRule
{
ErrorMessage = errorMessage,
ValidationType = "dategreaterthan" // This is the name the jQuery adapter will use, "startdatepropertyname" is the name of the jQuery parameter for the adapter, must be LOWERCASE!
};
dateGreaterThanRule.ValidationParameters.Add("startdatepropertyname", _startDatePropertyName);
yield return dateGreaterThanRule;
}
And created this JavaScript file:
(function ($) {
$.validator.addMethod("dategreaterthan", function (value, element, params) {
console.log("method");
return Date.parse(value) > Date.parse($(params).val());
});
$.validator.unobtrusive.adapters.add("dategreaterthan", ["startdatepropertyname"], function (options) {
console.log("adaptor");
options.rules["dategreaterthan"] = "#" + options.params.startdatepropertyname;
options.messages["dategreaterthan"] = options.message;
});
})(jQuery);
(Notice the console.log hits... I never see those.)
After this, I'm now getting hits when I browse to the page in the DataGreaterThanAttribute constructor and the GetClientValidationRules. As well, the ClassEnd input tag now has the following markup in it:
data-val-dategreaterthan="The field {0} is invalid." data-val-dategreaterthan-startdatepropertyname="ClassStart"
So I'm getting closer. The problem is, the addMethod and adapater.add don't seem to be doing their jobs. When I inspect these objects in the console using the following:
$.validator.methods
$.validator.unobtrusive.adapters
...my added method and adapter are not there. If I run the code from my JavaScript file in the console, they do get added and are there. I also noticed that if I generally inspect the unobtrusive validation object with...
$("#studentManagementForm").data('unobtrusiveValidation')
...there is no evidence of my custom validation.
As I alluded earlier, there are many examples out here, and they all seem to do things just a little differently, so I'm still trying some different things. But I'm really hoping someone who has beaten this into submission before will come along and share that hammer with me.
If I can't get this to work, I'll be putting on the hard-hat and writing some hacky JavaScript to spoof the same functionality.
I think you need IEnumerable<ValidationResult> on your model.
I had to do something similar around 4 years ago and still have the snippet to hand if this helps:
public class ResultsModel : IValidatableObject
{
[Required(ErrorMessage = "Please select the from date")]
public DateTime? FromDate { get; set; }
[Required(ErrorMessage = "Please select the to date")]
public DateTime? ToDate { get; set; }
IEnumerable<ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
var result = new List<ValidationResult>();
if (ToDate < FromDate)
{
var vr = new ValidationResult("The to date cannot be before the from date");
result.Add(vr);
}
return result;
}
}

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})
}

ASP.NET MVC 4 Custom Validation not working

I am trying to use a custom validation but its been ignored. I do not get any errors or anything. It simply does nothing. What am i doing wrong? Thank you for reading.
---ModelMetadata.cs----
using System.ComponentModel.DataAnnotations;
using myproject.Common;
namespace myproject.Models
{
[MetadataType(typeof(ModelMetaData))]
public partial class Reference
{
}
public class ModelMetaData {
[Required]
[Display(Name = "Full Name *")]
[ExcludeCharacters("/.,!##$%")] // <<<====== This is being ignored.
public string Name { get; set; }
}
}
--Create.cshtml ----
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
#using (Html.BeginForm()){
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="editor-field">
#Html.EditorFor(model => model.Name) // <<<====== field
#Html.ValidationMessageFor(model => model.Name)
</div>
--ExcludeCharacters.cs ---
namespace myproject.Common
{
public class ExcludeCharacters : ValidationAttribute
{
private readonly string _chars;
public ExcludeCharacters(string chars) : base("{0} contains invalid characters")
{
_chars = chars;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
for (int i = 0; i < _chars.Length; i++)
{
var valueAsString = value.ToString();
if (valueAsString.Contains(_chars[i].ToString()))
{
var errorMessage = FormatErrorMessage(validationContext.DisplayName);
return new ValidationResult(errorMessage);
}
}
}
return ValidationResult.Success;
}
}
}
Please check the action method in your controller - make sure the model type is used by a parameter, e.g.
public ActionResult Foo(ModelMetaData model)
i had exactly same problem, and was using same codes as well. i simply shutdown my application and restarted again. it worked for me. try this
Your code generally looks about right. This would validate, however, at the server side, the way you generally have it and if it was working. Moreover, I'm unsure of why some examples are only overriding the ValidationResult version of the IsValid method, and yet other examples are only overriding the bool variant.
If you want client side validation, you need to implement IClientValidatable , and register the adapter on the client side.
Below is some code I was able to make work. I needed to include my js file after my validation inclusion, and since I was using DevExpress with include client libraries, I needed to run it after them as well.
You'll also (for client side to work), want to use EditorFor or TextBoxFor type methods to add the fields, but this appears to be something you are already doing. Do, however, check your html and look for said validation proprieties being added.
I've tested this with my MM/dd/yyyy fields.
RangeSmallDateTime.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace YourNamespaceHere.Filters
{
public class RangeSmallDateTime : ValidationAttribute, IClientValidatable
{
private static DateTime _minValue = new DateTime(1900, 1, 1);
private static DateTime _maxValue = new DateTime(2079, 6, 6);
public override bool IsValid(object value)
{
DateTime? dateValue = value as DateTime?;
if (!dateValue.HasValue)
{
return true;
}
else
{
return (dateValue.Value >= _minValue && dateValue.Value <= _maxValue);
}
}
public override string FormatErrorMessage(string name)
{
return string.Format("The '{0}' field has an invalid value.", name);
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
ModelClientValidationRule rule = new ModelClientValidationRule();
rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
rule.ValidationType = "rangesdt";
yield return rule;
}
}
}
SmallDateTimeValidator.js:
$.validator.unobtrusive.adapters.addBool("rangesdt");
$.validator.addMethod("rangesdt", function (value, element) {
if (value == null) {
return true;
}
var date = new Date(value); // MM/dd/yyyy
var minDate = new Date(1900,1,1);
var maxDate = new Date(2079, 6, 6);
if (!dates.inRange(date, minDate, maxDate))
return false;
return true;
});
// Source: http://stackoverflow.com/questions/497790
var dates = {
convert: function (d) {
// Converts the date in d to a date-object. The input can be:
// a date object: returned without modification
// an array : Interpreted as [year,month,day]. NOTE: month is 0-11.
// a number : Interpreted as number of milliseconds
// since 1 Jan 1970 (a timestamp)
// a string : Any format supported by the javascript engine, like
// "YYYY/MM/DD", "MM/DD/YYYY", "Jan 31 2009" etc.
// an object : Interpreted as an object with year, month and date
// attributes. **NOTE** month is 0-11.
return (
d.constructor === Date ? d :
d.constructor === Array ? new Date(d[0], d[1], d[2]) :
d.constructor === Number ? new Date(d) :
d.constructor === String ? new Date(d) :
typeof d === "object" ? new Date(d.year, d.month, d.date) :
NaN
);
},
compare: function (a, b) {
// Compare two dates (could be of any type supported by the convert
// function above) and returns:
// -1 : if a < b
// 0 : if a = b
// 1 : if a > b
// NaN : if a or b is an illegal date
// NOTE: The code inside isFinite does an assignment (=).
return (
isFinite(a = this.convert(a).valueOf()) &&
isFinite(b = this.convert(b).valueOf()) ?
(a > b) - (a < b) :
NaN
);
},
inRange: function (d, start, end) {
// Checks if date in d is between dates in start and end.
// Returns a boolean or NaN:
// true : if d is between start and end (inclusive)
// false : if d is before start or after end
// NaN : if one or more of the dates is illegal.
// NOTE: The code inside isFinite does an assignment (=).
return (
isFinite(d = this.convert(d).valueOf()) &&
isFinite(start = this.convert(start).valueOf()) &&
isFinite(end = this.convert(end).valueOf()) ?
start <= d && d <= end :
NaN
);
}
}

ASP.NET MVC and Razor to display integer or blank when 0

If I have an integer value that I want to display on a page, I can do that a number of ways:
<span>#Html.DisplayFor(modelItem => item.UserId)</span>
<span>#item.UserId</span>
But what is the best way to convert that to displaying the value IF UserId != 0. But if UserId == 0, display an empty string. Is there a way to do it right in Razor syntax or do I need to head to code?
Create an extension method for int:
public static class IntExtensions
{
public static string EmptyIfZero(this int value)
{
if(value == 0)
return string.Empty;
return value.ToString();
}
}
... and then in your Razor view, do:
<span>#item.UserId.EmptyIfZero()</span>
<span>#((item.UserID == 0) ? "" : #item.UserID.ToString())</span>
OR
<span>#if(item.UserID == 0) { <span></span> }
else { #Html.DisplayFor(m => item.UserID); }
</span>
I think you could do this with one if condition
<span>#if(item.UserID != 0) { #Html.DisplayFor(m => item.UserID); } //the browser would render empty string by itself
To render content without putting the redundant (as you said) <span>, use the #: - MVC3 Razor: Displaying html within code blocks and #: for displaying content
<span>
#if(item.UserID == 0) { } //this is redundant too
else { #Html.DisplayFor(m => item.UserID);
}
</span>
Note that I have moved the } to next line. ASP.Net MVC did not accept it
<span>
#if(item.UserID == 0) { #:Some content with no html tag wrapper
}
else { #Html.DisplayFor(m => item.UserID);
}
</span>
You can do this:
<span>#(item.UserId != 0 ? item.UserId.ToString() : string.Empty)</span>
I think the best and most reusable would be to create a template.
So you create e.g. UserId.vbhtml in ~/Views/Shared/DisplayTemplates
with the following content:
in the template you build all the logic, which would be something like (I am typing without checking and I usually code in VB, so there may be mistakes):
#model int
#((Model == 0) ? "" : #Model)
And then in the code you use:
#Html.DisplayFor(modelItem => item.UserId, "UserId")
You can also put UIHint attribute over UserId in your class: [UIHint("UserId")]
and then you do not need to provide the template name.
This is another way to display integer or blank when model value is 0.
Model:
[Display(Name = "User Id")]
public int UserId { get; set; }
View:
<span>
#Html.DisplayNameFor(m => m.UserId)
</span>
<span>
#Html.TextBoxFor(m => m.UserId, new { #Value = (Model.UserId > 0 ? Model.UserId.ToString() : string.Empty) })
</span>
I did some more global solution, display blank for:
- integer: 0
- decimal: 0.0
- string: "0x0" or "0x0x0"
Extension class:
public static class DataTypesExtension
{
static string[] Keywords = { "0", "0.0", "0.00", "0.000", "0.0000", "0,0", "0,00", "0,000", "0,0000", "0x0", "0x0x0" };
public static string BlankIfZero(this object n)
{
string ret = string.Empty;
if (n == null)
return ret;
string sn = n.ToString().Replace(" ", "");
if (!DataTypesExtension.Keywords.Contains(sn))
ret = n.ToString();
return ret;
}
}
Display template:
#model object
#using MyProject.Extensions;
#{
string val = Model.BlankIfZero();
#val;
}
And in View Model:
[UIHint("BlankIfZero")]
public int? MyIntProperty { get; set; }
[UIHint("BlankIfZero")]
public decimal? MyDecimalProperty { get; set; }
[UIHint("BlankIfZero")]
public string MyStringProperty { get; set; }
On my case, i found this to be easier:
$(document).ready(function () {
$("#myField").val("");
}
Not sure if this is wahat you were looking for, but worked fine for me.

MVC3 unobtrusive validation group of inputs

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.

Resources