Custom ValidationAttribute doesn't work
Asked Answered
F

1

7

I tried to create a custom ValidationAttribute:

public class RollType : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        return false;   // just for trying...
    }
}

Then I created (in another class) -

  [RollType]
  [Range(0,4)]
  public int? Try { get; set; }

on the view (I use MVC) I wrote:

      <div class="editor-label">
            Try:
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Try)
            @Html.ValidationMessageFor(model => model.Try)
        </div>

The validation for "range" works great, but not for the custom one!

What can be the problem?

Frow answered 25/4, 2012 at 6:12 Comment(1)
Note that RollTypeAttribute is the recommended name for this class. You can still use [RollType] with that new name.Millionaire
S
8

Try this

public class RollType : ValidationAttribute
{
   protected override ValidationResult IsValid(object value, ValidationContext validationContext)
   {
      return new ValidationResult("Something went wrong");
   }
}

Also do not forget to check if modelstate is valid in code behind or else it won't work, Example

    [HttpPost]
    public ActionResult Create(SomeObject object)
    {
        if (ModelState.IsValid)
        {
            //Insert code here
            return RedirectToAction("Index");
        }
        else
        {
            return View();
        }
    }
Sketchy answered 25/4, 2012 at 6:37 Comment(4)
"Error 1 'RollType.IsValid(object, System.ComponentModel.DataAnnotations.ValidationContext)': cannot change access modifiers when overriding 'protected' inherited member 'System.ComponentModel.DataAnnotations.ValidationAttribute.IsValid(object, System.ComponentModel.DataAnnotations.ValidationContext)' "Frow
Sorry I just fixed the mistake, it need to be protected override not public override, it will work now.Sketchy
Also if you want to ass a success message use 'return ValidationResult.Success;'Sketchy
Thanks! I deleted everything I did and start from begining and used your code and now it works.. :)Frow

© 2022 - 2024 — McMap. All rights reserved.