How can I extend a DataAnnotation attribute and have client side validation work? - asp.net-core-mvc

In a large number of places on my model, I have a property public int CarrotLength {get; set;} I want to put a [Range(5, 100)] attribute on it.
Rather than have to specify this millions of times for every CarrotLength property, because the carrot length might change, it makes sense to make a [CarrotLength] attribute instead so I can just change the values 5 and 10 in one place.
I made a public class CarrotLengthAttribute : RangeAttribute and call the base class with 5, 100. However the client side unobtrusive javascript validation doesn't trigger.
Is there a way to make it work? Possibly I need to register the attribute somehow?
My unobtrusive javascript validation works for normal attributes, as well as custom ones that I have created.
If it's not possible I will just define the values as constants and reference them as [Range(MYCONSTS.CARROTLENGTHMIN...)] but I think it's nicer to have a custom attribute.

Try customing the attribute class that inherits from the ValidationAttribute and IClientModelValidator like below :
public class AgeRangeAttribute: ValidationAttribute , IClientModelValidator
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var age = Convert.ToInt32(value.ToString());
if (age<5||age>100)
{
return new ValidationResult(GetErrorMessage());
}
return ValidationResult.Success;
}
public string GetErrorMessage()
{
return $"Age must be between 5 and 100.";
}
public void AddValidation(ClientModelValidationContext context)
{
context.Attributes.Add("data-val", "true");
context.Attributes.Add("data-val-age", GetErrorMessage());
}
}
Add a new JavaScript file named AgeValidate.js into the wwwroot folder "/lib/jquery-validation-unobtrusive/AgeValidate.js" :
jQuery.validator.addMethod("age",
function (value, element, param) {
if (value < 5 || value > 100) {
return false;
}
else {
return true;
}
});
jQuery.validator.unobtrusive.adapters.addBool("age");
The above code adds a method to jQuery validation library. It uses addMethod() method to specify our own validation function. The validation function receives the value entered in the age textbox. It then performs the validation and returns a boolean value.
Reference the AgeValidate.js in _ValidationScriptsPartial.cshtml
<environment include="Development">
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js">
</script>
<script src="~/lib/jquery-validation-unobtrusive/AgeValidate.js"></script>
</environment>
Add the below code in your view
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
For more details on customizing client-side validation , you could refer to the official documentation: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-2.2#custom-client-side-validation

Related

EF, POCO, DbContext and Validating Deletions

I'm fairly new to the world of MVC and EF, and I've come quite a ways on my own, but one thing I haven't been able to find online is how people validate for "do not delete" conditions.
I'm using EF4.1 database-first POCO classes generated with the DbContext T4 template. In my partial class files I've already decorated all of my classes with the "IValidatableObject" interface that gets called on changes for my business rules that go beyond the standard MetaData attribute type of validations.
What I need now is a validation that works via the same mechanism (and is, therefore, transparent to the UI and the controller) for checking if deletions are OK. My thought was to create an interface like so:
public interface IDeletionValidation
{
DbEntityValidationResult ValidateDeletion(DbEntityValidationResult validationResults);
}
...and then do this in an override to ValidateEntity in the DbContext...
public partial class MyEntityContext
{
protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items)
{
DbEntityValidationResult val = base.ValidateEntity(entityEntry, items);
if (entityEntry.State == EntityState.Deleted)
{
IDeletionValidation delValidationEntity = entityEntry.Entity as IDeletionValidation;
if (delValidationEntity != null)
val = delValidationEntity.ValidateDeletion(val);
}
return val;
}
...and then I could implement the IDeletionValidation interface on those classes that need to have a validation done before they can be safely deleted.
An example (not working, see caveat in comments) of the ValidateDeletion code would be...
public partial class SalesOrder : IDeletionValidation, IValidatableObject
{
public DbEntityValidationResult ValidateDeletion(DbEntityValidationResult validations)
{
// A paid SalesOrder cannot be deleted, only voided
// NOTE: this code won't work, it's coming from my head and note from the actual source, I forget
// what class I'd need to add to the DbEntityValidationResult collection for this type of validation!
if (PaidAmount != 0)
validations.Add(new ValidationResult("A paid SalesOrder cannot be deleted, only voided"));
return validations;
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
List<ValidationResult> validations = new List<ValidationResult>();
// Verify that the exempt reason is filled in if the sales tax flag is blank
if (!IsTaxable && string.IsNullOrEmpty(TaxExemptReason))
validations.Add(new ValidationResult("The Tax Exempt Reason cannot be blank for non-taxable orders"));
return validations;
}
....
}
Am I on the right track? Is there a better way?
Thanks,
CList
EDIT --- Summary of the one-interface method proposed by Pawel (below)
I think the one-interface way presented below and my way above is a little bit of a chocolate vs. vanilla argument in terms of how you want to do it. Performance should be about the same for large numbers of updates / deletes, and you may want to have your delete validation be a separate interface that doesn't apply to all of your validated classes, but if you want all of your validations in one place here it is...
Mod your DBContext
protected override bool ShouldValidateEntity(DbEntityEntry entityEntry)
{
return entityEntry.Sate == EntityState.Deleted ||
base.ShouldValidateEntity(entityEntry);
}
protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items)
{
var myItems = new Dictionary<object, object>();
myItems.Add("IsDelete", (entityEntry.State == EntityState.Deleted));
// You could also pass the whole context to the validation routines if you need to, which might be helpful if the
// validations need to do additional lookups on other DbSets
// myItems.Add("Context", this);
return base.ValidateEntity(entityEntry, myItems);
}
Put the deletion-validation in your entity's Validate
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
List<ValidationResult> validations = new List<ValidationResult>();
bool isDelete = validationContext.Items.ContainsKey("IsDelete")
? (bool)validationContext.Items["IsDelete"]
: false;
if (isDelete)
{
if (PaidAmount != 0)
validations.Add(new ValidationResult("You cannot delete a paid Sales Order Line", new string[] { "PaidAmount" }));
return validations;
}
// Update / Add validations!!
// Verify that the exempt reason is filled in if the sales tax flag is blank
if (!IsTaxable && string.IsNullOrEmpty(TaxExemptReason))
validations.Add(new ValidationResult("The Tax Exempt Reason cannot be blank for non-taxable orders"));
return validations;
}
...and in the interest of brevity and only putting all of the check-if-delete code in one place, you could even create an extension method on the ValidationContext class (if you're into that sort of thing) like so...
public static class MyExtensions
{
public static bool IsDelete(this System.ComponentModel.DataAnnotations.ValidationContext validationContext)
{
return validationContext.Items.ContainsKey("IsDelete")
? (bool)validationContext.Items["IsDelete"]
: false;
}
}
...which gives us this for our validation code...
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
List<ValidationResult> validations = new List<ValidationResult>();
if (validationContext.IsDelete())
{
....
I am not really sure why you need a separate interface just for deleted entities. You could pass the entity state (or the EntityEntry object, or the context) to your IValidatableObject.Validate() method by using the items dictionary you pass to the base.ValidateEntity() method. Take a look at the "Custom Validation Sample: Uniqness" section in this blog post http://blogs.msdn.com/b/adonet/archive/2011/05/27/ef-4-1-validation.aspx. This way you could do everything using just one interface - IValidatableObject.
In addition to that - by default EF validates only Added and Modified entities. If you want to validate entities that are in the Deleted state you need to override DbContext.ShouldValidateEntity() method with something like this:
protected override bool ShouldValidateEntity(DbEntityEntry entityEntry)
{
return entityEntry.Sate == EntityState.Deleted ||
base.ShouldValidateEntity(entityEntry);
}

Get full name of Complex Type from ModelClientValidationRequiredIfRule method in custom ValidationAttribute

I am using the example at The Complete Guide To Validation In ASP.NET MVC 3 to create a RequiredIf validation attribute (it's about 1/3 down the page under the heading of "A more complex custom validator"). It all works fine with the exception of one scenario, and that is if I have the need to validate against a complex type. For example, I have the following model:
public class MemberDetailModel
{
public int MemberId { get; set; }
// Other model properties here
public MemberAddressModel HomeAddress { get; set; }
public MemberAddressModel WorkAddress { get; set; }
}
public class MemberAddressModel
{
public bool DontUse { get; set; }
// Other model properties here
[RequiredIf("DontUse", Comparison.IsEqualTo, false)]
public string StreetAddress1 { get; set; }
}
The problem is that when the attribute validation for the StreetAddress property is rendered, it get's decorated with the attribute of data-val-requiredif-other="DontUse". Unfortunately, since the address is a sub-type of the main model, it needs to be decorated with a name of HomeAddress_DontUse and not just DontUse.
Strangely enough, the validation works fine for server-side validation, but client-side unobtrusive validation fails with an JS error because JS can't find the object with a name of just "DontUse".
Therefore, I need to find a way to change the ModelClientValidationRequiredIfRule method to know that the property it is validating is a sub-type of a parent type, and if so, prepend the ParentType_ to the "otherProperty" field (e.g. otherProperty becomes HomeAddress_DontUse.
I have tried passing in typeof(MemberAddressModel) as a parameter of the attribute, but even when debugging the attribute creation, I can't seem to find any reference to the parent type of HomeAddress or WorkAddress from that type.
Based on the suggestion from The Flower Guy, I was able to come up with the following which seems to work. I simply modified the following in the customValidation.js file:
jQuery.validator.addMethod("requiredif", function (value, element, params) {
if ($(element).val() != '') return true;
var prefix = getModelPrefix(element.name); // NEW LINE
var $other = $('#' + prefix + params.other); // MODIFIED LINE
var otherVal = ($other.attr('type').toUpperCase() == "CHECKBOX") ? ($other.attr("checked") ? "true" : "false") : $other.val();
return params.comp == 'isequalto' ? (otherVal != params.value) : (otherVal == params.value);
});
I also added the following method to that file (within the JQuery block so as to be only privately accessible):
function getModelPrefix(fieldName) {
return fieldName.substr(0, fieldName.lastIndexOf(".") + 1).replace(".","_");
}
Cannot do it exactly right now, but the problem is in the client javascript function:
jQuery.validator.addMethod("requiredif" ...
The js is not sophisticated enough to cope with complex view models where there may be a model prefix. If you take a look at Microsoft's jquery.validate.unobstrusive.js (in the Scripts folder over every MVC3 application), you will find some useful methods including getModelPrefix and appendModelPrefix. You can take a similar approach and change the requiredIf validation method - take a look at the equalto method in jquery.validate.unobstrusive.js for a helping hand.

Validate checkbox on the client with FluentValidation/MVC 3

I am trying to validate if a check box is checked on the client using FluentValidation. I can't figure it our for the life of me.
Can it be done using unobtrusive validation?
Let's assume that you have the following model:
[Validator(typeof(MyViewModelValidator))]
public class MyViewModel
{
public bool IsChecked { get; set; }
}
with the following validator:
public class MyViewModelValidator : AbstractValidator<MyViewModel>
{
public MyViewModelValidator()
{
RuleFor(x => x.IsChecked).Equal(true).WithMessage("Please check this checkbox");
}
}
and a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
with a corresponding view:
#model MyViewModel
#using (Html.BeginForm())
{
#Html.LabelFor(x => x.IsChecked)
#Html.CheckBoxFor(x => x.IsChecked)
#Html.ValidationMessageFor(x => x.IsChecked)
<button type="submit">OK</button>
}
and in Global.asax you have registered the fluent validation model validator provider:
FluentValidationModelValidatorProvider.Configure();
So far we have server side validation up and running fine. That's good. That's always the first part that we must setup. I have seen people focusing too much on doing client side validation that they forget doing server side validation and when you disable javascript (or even worse if you stumble upon a user with bad intentions), well, bad things happen.
So far we are confident because we know that even if something gets screwed up on the client our domain is protected with server side validation.
So let's now take care for the client validation. Out of the box FluentValidation.NET supports automatic client validation for the EqualTo validator but when comparing against another property value which is the equivalent of the [Compare] data annotation.
But in our case we are comparing against a fixed value. So we don't get client side vaildation out of the box. And when we don't get something out of the box, we need to put it in the box.
So we start by defining a custom FluentValidationPropertyValidator:
public class EqualToValueFluentValidationPropertyValidator : FluentValidationPropertyValidator
{
public EqualToValueFluentValidationPropertyValidator(ModelMetadata metadata, ControllerContext controllerContext, PropertyRule rule, IPropertyValidator validator)
: base(metadata, controllerContext, rule, validator)
{
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
if (!this.ShouldGenerateClientSideRules())
{
yield break;
}
var validator = (EqualValidator)Validator;
var errorMessage = new MessageFormatter()
.AppendPropertyName(Rule.GetDisplayName())
.AppendArgument("ValueToCompare", validator.ValueToCompare)
.BuildMessage(validator.ErrorMessageSource.GetString());
var rule = new ModelClientValidationRule();
rule.ErrorMessage = errorMessage;
rule.ValidationType = "equaltovalue";
rule.ValidationParameters["valuetocompare"] = validator.ValueToCompare;
yield return rule;
}
}
that we are going to register in Application_Start:
FluentValidationModelValidatorProvider.Configure(provider =>
{
provider.AddImplicitRequiredValidator = false;
provider.Add(typeof(EqualValidator), (metadata, context, description, validator) => new EqualToValueFluentValidationPropertyValidator(metadata, context, description, validator));
});
So far we have associated our custom FluentValidationPropertyValidator with the EqualValidator.
The last part is to write a custom adapter:
(function ($) {
$.validator.unobtrusive.adapters.add('equaltovalue', ['valuetocompare'], function (options) {
options.rules['equaltovalue'] = options.params;
if (options.message != null) {
options.messages['equaltovalue'] = options.message;
}
});
$.validator.addMethod('equaltovalue', function (value, element, params) {
if ($(element).is(':checkbox')) {
if ($(element).is(':checked')) {
return value.toLowerCase() === 'true';
} else {
return value.toLowerCase() === 'false';
}
}
return params.valuetocompare.toLowerCase() === value.toLowerCase();
});
})(jQuery);
And that's pretty much it. All that's left is to include the client scripts:
<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 src="#Url.Content("~/Scripts/customadapter.js")" type="text/javascript"></script>
I like the Darin Dimitrov's answer, but if you want to do it quickly, here is my alternative way.
Create an additional property in your model, e.g.:
public bool ValidationTrue { get; set; }
and set its value to true in the model's contructor.
Use it in your view to save the value across the requests:
#Html.HiddenFor(x => x.ValidationTrue)
Now add a validation rule like this:
public class MyViewModelValidator : AbstractValidator<MyViewModel>
{
public MyViewModelValidator()
{
RuleFor(x => x.ValidationTrue)
.Equal(true); // check it for security reasons, if someone has edited it in the source of the page
RuleFor(x => x.HasToBeChecked)
.Equal(x => x.ValidationTrue) // HasToBeChecked has to have the same value as ValidationTrue (which is always true)
.WithMessage("Required");
}
}
That validation is supported by the unobtrusive validator out-of-the-box.
I am coding in ASP.NET MVC5 and Darin's code produces a javascript error on the lines that reference value.ToLowerCase() when a checkbox is involved. Another issue is that this code invalidates the client side equality comparison between two properties. It only seems to work when comparing against a literal value...That may have been his intent, but I need it to work for both situations:
Here's one possible workaround, that involves only two changes to Darin's answer:
First, I updated the javascript function with the following.
$.validator.addMethod('equaltovalue', function (value, element, params) {
if ($(element).is(':checkbox')) {
value = $(element).is(':checked') ? "true" : "false";
}
return params.valuetocompare.toLowerCase() === value.toLowerCase();
});
Secondly, I updated EqualToValueFluentValidationPropertyValidator with the following:
public class EqualToValueFluentValidationPropertyValidator : FluentValidationPropertyValidator
{
EqualValidator EqualValidator
{
get { return (EqualValidator)Validator; }
}
public EqualToValueFluentValidationPropertyValidator(ModelMetadata metadata, ControllerContext controllerContext, PropertyRule rule, IPropertyValidator validator) : base(metadata, controllerContext, rule, validator) {
ShouldValidate = false;
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() {
if (!ShouldGenerateClientSideRules()) yield break;
var propertyToCompare = EqualValidator.MemberToCompare as PropertyInfo;
if(propertyToCompare != null) {
// If propertyToCompare is not null then we're comparing to another property.
// If propertyToCompare is null then we're either comparing against a literal value, a field or a method call.
// We only care about property comparisons in this case.
var comparisonDisplayName =
ValidatorOptions.DisplayNameResolver(Rule.TypeToValidate, propertyToCompare, null)
?? propertyToCompare.Name.SplitPascalCase();
var formatter = new MessageFormatter()
.AppendPropertyName(Rule.GetDisplayName())
.AppendArgument("ComparisonValue", comparisonDisplayName);
string message = formatter.BuildMessage(EqualValidator.ErrorMessageSource.GetString());
yield return new ModelClientValidationEqualToRule(message, CompareAttribute.FormatPropertyForClientValidation(propertyToCompare.Name)) ;
}
else
{
var validator = (EqualValidator)Validator;
var errorMessage = new MessageFormatter()
.AppendPropertyName(Rule.GetDisplayName())
.AppendArgument("ValueToCompare", validator.ValueToCompare)
.BuildMessage(validator.ErrorMessageSource.GetString());
var rule = new ModelClientValidationRule();
rule.ErrorMessage = errorMessage;
rule.ValidationType = "equaltovalue";
rule.ValidationParameters["valuetocompare"] = validator.ValueToCompare;
yield return rule;
}
}
}
This code was copied from the EqualToFluentValidationPropertyValidator internal class in the fluentvalidation source, and I added Darin's logic after the else. This allows the client-side validation to work for property comparisons as well as value comparisons...I'm not sure if this is a great approach since you're basically overriding the built-in equality validator and it may break in future releases of fluent validation....but Darin's answer has the same issue.
There might be better ways to handle this. If somebody knows of a way to directly include the logic from the internal EqualToFluentValidationPropertyValidator class, then I'd love to hear it.
it's based on #cryss answer
RuleFor(x => x.HasToBeChecked)
.Equal(x => true)
.WithMessage("Required");
you don't need to use additional property

MVC 3 Complicated validation of models

Current validation method for use in MVC 3 seems to be ValidationAttributes. I have a class validation that is very specific to that model and has interactions between a few properties.
Basically the model has a collection of other models and they are edited all in the same form. Let's call it ModelA and it has a collection of ModelB. One thing I might have to validate is that the sum of the some property of ModelB is less then a property of ModelA. The user has X number of points he can divide among some options.
ValidationAttributes are very generic and I'm not sure they are suited for this job.
I have no idea how IDateErrorInfo is supported in MVC 3 and whether it works straight out of the box.
One way would be to validate through a method but that means I can't do a clientside validation.
What is the proper way to do something like this? Are there any more options I have? Am I underestimating the power of ValidationAttribute?
IDateErrorInfo
IDateErrorInfo is supported by the MVC framework (a Microsoft tutorial can be found here). The default model binder will be reponsible for recreating model objects by binding the html form elements to the model. If the model binder detects that the model implements the interface then it will use the interface methods to validate each property in the model or to validate the model as a whole. See the tutorial for more information.
If you wanted to use client side validation using this method then (to quote Steve Sanderson) 'the most direct way to take advantage of additional validation rules is to manually generate the required attributes in the view':
<p>
#Html.TextBoxFor(m.ClientName, new { data_val = "true", data_val_email = "Enter a valid email address", data_val_required = "Please enter your name"})
#Html.ValidationMessageFor(m => m.ClientName)
</p>
This can then be used to trigger any client side validation that has been defined. See below for an example of how to define client side validation.
Explicit Validation
As you mentioned, you could explicity validate the model in the action. For example:
public ViewResult Register(MyModel theModel)
{
if (theModel.PropertyB < theModel.PropertyA)
ModelState.AddModelError("", "PropertyA must not be less then PropertyB");
if (ModelState.IsValid)
{
//save values
//go to next page
}
else
{
return View();
}
}
In the view you would then need to use #Html.ValidationSummary to display the error message as the above code would add a model level error and not a property level error.
To specify a property level error you can write:
ModelState.AddModelError("PropertyA", "PropertyA must not be less then PropertyB");
And then in the view use:
#Html.ValidationMessageFor(m => m.PropertyA);
to display the error message.
Again, any client side validation would need to be linked in by manually linking in the client side validation in the view by defining properties.
Custom Model Validation Attribute
If I understand the problem correctly, you are trying to validate a model which contains a single value and a collection where a property on the collection is to be summed.
For the example I will give, the view will present to the user a maximum value field and 5 value fields. The maximum value field will be a single value in the model where as the 5 value fields will be part of a collection. The validation will ensure that the sum of the value fields is not greater than the maximum value field. The validation will be defined as an attribute on the model which will also link in nicely to the javascript client side valdation.
The View:
#model MvcApplication1.Models.ValueModel
<h2>Person Ages</h2>
#using (#Html.BeginForm())
{
<p>Please enter the maximum total that will be allowed for all values</p>
#Html.EditorFor(m => m.MaximumTotalValueAllowed)
#Html.ValidationMessageFor(m => m.MaximumTotalValueAllowed)
int numberOfValues = 5;
<p>Please enter #numberOfValues different values.</p>
for (int i=0; i<numberOfValues; i++)
{
<p>#Html.EditorFor(m => m.Values[i])</p>
}
<input type="submit" value="submit"/>
}
I have not added any validation against the value fields as I do not want to overcomplicate the example.
The Model:
public class ValueModel
{
[Required(ErrorMessage="Please enter the maximum total value")]
[Numeric] //using DataAnnotationExtensions
[ValuesMustNotExceedTotal]
public string MaximumTotalValueAllowed { get; set; }
public List<string> Values { get; set; }
}
The Actions:
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(ValueModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
else
{
return RedirectToAction("complete"); //or whatever action you wish to define.
}
}
The Custom Attribute:
The [ValuesMustNotExceedTotal] attribute defined on the model can be defined by overriding the ValidationAttribute class:
public class ValuesMustNotExceedTotalAttribute : ValidationAttribute
{
private int maxTotalValueAllowed;
private int valueTotal;
public ValuesMustNotExceedTotalAttribute()
{
ErrorMessage = "The total of all values ({0}) is greater than the maximum value of {1}";
}
public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, valueTotal, maxTotalValueAllowed);
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
PropertyInfo maxTotalValueAllowedInfo = validationContext.ObjectType.GetProperty("MaximumTotalValueAllowed");
PropertyInfo valuesInfo = validationContext.ObjectType.GetProperty("Values");
if (maxTotalValueAllowedInfo == null || valuesInfo == null)
{
return new ValidationResult("MaximumTotalValueAllowed or Values is undefined in the model.");
}
var maxTotalValueAllowedPropertyValue = maxTotalValueAllowedInfo.GetValue(validationContext.ObjectInstance, null);
var valuesPropertyValue = valuesInfo.GetValue(validationContext.ObjectInstance, null);
if (maxTotalValueAllowedPropertyValue != null && valuesPropertyValue != null)
{
bool maxTotalValueParsed = Int32.TryParse(maxTotalValueAllowedPropertyValue.ToString(), out maxTotalValueAllowed);
int dummyValue;
valueTotal = ((List<string>)valuesPropertyValue).Sum(x => Int32.TryParse(x, out dummyValue) ? Int32.Parse(x) : 0);
if (maxTotalValueParsed && valueTotal > maxTotalValueAllowed)
{
return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
}
}
//if the maximum value is not supplied or could not be parsed then we still return that the validation was successful.
//why? because this attribute is only responsible for validating that the total of the values is less than the maximum.
//we use a [Required] attribute on the model to ensure that the field is required and a [Numeric] attribute
//on the model to ensure that the fields are input as numeric (supplying appropriate error messages for each).
return null;
}
}
Adding Client Side Validation to the Custom Attribute:
To add client side validation to this attribute it would need to implement the IClientValidatable interface:
public class ValuesMustNotExceedTotalAttribute : ValidationAttribute, IClientValidatable
{
//...code as above...
//this will be called when creating the form html to set the correct property values for the form elements
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule {
ValidationType = "valuesmustnotexceedtotal", //the name of the client side javascript validation (must be lowercase)
ErrorMessage = "The total of all values is greater than the maximum value." //I have provided an alternative error message as i'm not sure how you would alter the {0} and {1} in javascript.
};
yield return rule;
//note: if you set the validation type above to "required" or "email" then it would use the default javascript routines (by those names) to validate client side rather than the one we define
}
}
If you were to run the application at this point and view the source html for the field defining the attribute you will see the following:
<input class="text-box single-line" data-val="true" data-val-number="The MaximumTotalValueAllowed field is not a valid number." data-val-required="Please enter the maximum total value" data-val-valuesmustnotexceedtotal="The total of all values is greater than the maximum value." id="MaximumTotalValueAllowed" name="MaximumTotalValueAllowed" type="text" value="" />
In particular notice the validation attribute of data-val-valuesmustnotexceedtotal. This is how our client side validation will link to the validation attribute.
Adding Client Side Validation:
To add client side validation you need to add the following similar library references in the tag of the view:
<script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
You need to also ensure that the client side validation is switched on in the web.config although I think this should be on by default:
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
All that is left is to define the client side validation in the view. Note that the validation added here is defined in the view but if it was defined in a library then the custom attribute (maybe not this one) could be added to other models for other views:
<script type="text/javascript">
jQuery.validator.unobtrusive.adapters.add('valuesmustnotexceedtotal', [], function (options) {
options.rules['valuesmustnotexceedtotal'] = '';
options.messages['valuesmustnotexceedtotal'] = options.message;
});
//note: this will only be fired when the user leaves the maximum value field or when the user clicks the submit button.
//i'm not sure how you would trigger the validation to fire if the user leaves the value fields although i'm sure its possible.
jQuery.validator.addMethod('valuesmustnotexceedtotal', function (value, element, params) {
sumValues = 0;
//determine if any of the value fields are present and calculate the sum of the fields
for (i = 0; i <= 4; i++) {
fieldValue = parseInt($('#Values_' + i + '_').val());
if (!isNaN(fieldValue)) {
sumValues = sumValues + fieldValue;
valueFound = true;
}
}
maximumValue = parseInt(value);
//(if value has been supplied and is numeric) and (any of the fields are present and are numeric)
if (!isNaN(maximumValue) && valueFound) {
//perform validation
if (sumValues > maximumValue)
{
return false;
}
}
return true;
}, '');
</script>
And that should be it. I'm sure that there are improvements that can be made here and there and that if i've misunderstood the problem slightly that you should be able to tweak the validation for your needs. But I believe this validation seems to be the way that most developers code custom attributes including more complex client side validation.
Hope this helps. Let me know if you have any questions or suggestions regarding the above.
This is what you are looking for:
http://www.a2zdotnet.com/View.aspx?Id=182
I got some similar situation too, I need to compare the value of property A with property B, and I get it done by:
public sealed class PropertyAAttribute : ValidationAttribute
{
public string propertyBProperty { get; set; }
// Override the isValid function
public override bool IsValid(object value)
{
// Do your comparison here, eg:
return A >= B;
}
}
Then just use the custom validation attribute like this:
[PropertyA(propertyBProperty = "PropertyB")]
public string Property A {get; set;}
I also tried very hard and get this solution from others, Hope this help!
Your model class can implement the IValidatableObject interface.
This way you have access to all the properties of your model class and can perform all your custom validations.
You also have the IClientValidatable interface, for client side validations, but I'm not sure if by implementing it directly in the model class the client validations are picked by MVC since I only ever used this interface to specify client validations in custom validation attributes.

Automatic mapping seems to not like 'Name' fields

I have a model that looks like this.
class Aspect {
Guid Id { get; set; }
string Name { get; set; }
string Description { get; set; }
// multiple other properties
}
In my View (ASP.NET MVC 3.0) I am trying to use the KnockoutJS mapping plugin. I call upon it like this. (Html Helpers listed beneath)
// attempt to bind any data we received from the server
var serverData = #Html.Interpret(Model);
// auto map the knockout attributes from the server data
var viewModel = ko.mapping.fromJS(serverData);
// apply the knockout binding to the viewModel
ko.applyBindings(viewModel, $("#__frmAspect")[0]);
// attach the jquery unobtrusive validator
$.validator.unobtrusive.parse("#__frmAspect");
viewModel.Save = function() {
// we will try to send the model to the server.
ko.utils.postJson(
$("#__frmAspect").attr('action'), { model: ko.toJS(viewModel) }
);
};
// bind the submit handler to unobtrusive validation.
$("#__frmAspect").data("validator").settings.submitHandler = viewModel.Save;
For the most part, this actually works. However, for whatever reason, it does not like the Name field.
It creates it, mind you. If I place a breakpoint at postJson in the knockout.js file, I can sit there and see that the ko.observable() does exist. It just is not getting set by the input field.
Can anyone tell me why this might be?
My Html Helpers:
namespace System.Web.Mvc {
public static class KnockoutHelpers {
public static MvcHtmlString Interpret<TModel>(this HtmlHelper htmlHelper, TModel model) {
return new MvcHtmlString(model.ToJson());
}
}
public static string ToJson ( this object item ) {
return new System.Web.Script.Serialization.JavaScriptSerializer( ).Serialize( item );
}
}
Looks like we got this solved on the KO forums. Autocomplete was not firing the change event on the Name field.
Defined the data bind like: data-bind="value: Name, valueUpdate: 'blur'" to make this work.

Resources