Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom ValidationAttribute doesn't work

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?

like image 271
TamarG Avatar asked Apr 25 '12 06:04

TamarG


1 Answers

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();
        }
    }
like image 166
Tenerezza Avatar answered Oct 04 '22 13:10

Tenerezza