Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>After spending a couple of hours looking around, I see no one really has a suitable answer to this. I have found a solution that works for me so I thought I'd post it.</p> <p>The problem for me was validating a nullable int. When a non valid value was entered by the user, the default message "The value 'dsfd' is not valid for Issue'.</p> <p>The solution I came up with was to remove the errors from the model state and add my own.</p> <p>The classes to perform the validation are below:</p> <pre><code>[AttributeUsage(AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = false)] public class ValidInteger : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value == null || value.ToString().Length == 0) { return ValidationResult.Success; } int i; return !int.TryParse(value.ToString(), out i) ? new ValidationResult(ErrorMessage) : ValidationResult.Success; } } public class ValidIntegerValidator : DataAnnotationsModelValidator&lt;ValidInteger&gt; { public ValidIntegerValidator(ModelMetadata metadata, ControllerContext context, ValidInteger attribute) : base(metadata, context, attribute) { if(!attribute.IsValid(context.HttpContext.Request.Form[attribute.ObjectId])) { var propertyName = metadata.PropertyName; context.Controller.ViewData.ModelState[propertyName].Errors.Clear(); context.Controller.ViewData.ModelState[propertyName].Errors.Add(attribute.ErrorMessage); } } } </code></pre> <p>Don't forget you'll also need to register the adapter in the global Application_Start()</p> <pre><code>DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(ValidInteger), typeof(ValidIntegerValidator)); </code></pre> <p>And decorate your property with the new attribute</p> <pre><code>[ValidInteger(ErrorMessage = "Please enter a valid number for issue")] </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload