0

I've an issue with validating user input in bootstrap modal before form submission. I have a class with this property

[FooValidation]
[MaxLength(50)]
[Required]
public string Foo {get;set;}

the foo property has to be unique so that's why I created FooValidation attribute which looks like this:

public class FooValidationAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        //logic
         return true;
    }
}

And in my view I have

@Html.TextBoxFor(model => model.Foo, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Foo)

Now the problem is, default attributes (Required and MaxLength) work just fine, when I try to submit the form I get the proper error messages, but my custom attribute doesn't, the IsValid method is called and returns proper value but the form gets submitted no matter what. Any idea what might be wrong?

PS: I tried to override this method

ValidationResult IsValid(object value, ValidationContext validationContext)

as well but the result is the same.

kulhajs
  • 132
  • 7

1 Answers1

0

The form will get submitted indeed. But ModelState.IsValid should return false and you should return to you view without updating the data:

public ActionResult SaveData(Model model)
{
    if (ModelState.IsValid)
    {
        // update here
        // then redirect to view
        return RedirectToAction("View", new { id = model.ID });
    }
    return View(model);
}

If you want to prevent your form from posting you should implement a Remote validation.

Add this in your model:

[Remote("IsFooUnique", AdditionalFields="ID", ErrorMessage="Foo is already in use")]
[MaxLength(50)]
[Required]
public string Foo {get;set;}

And this in your controller:

public JsonResult IsFooUnique(int ID, string Foo)
    {
        bool isUnique = false; // ... your logic here
        return Json(isUnique, JsonRequestBehavior.AllowGet);
    }

This will be validated in the client (either obtrusive or unobtrusive) and will prevent your form from being submitted. And will also validate on the server side, in the controller method that saves the data and will also set the ModelState.IsValid to false.

SmartDev
  • 2,802
  • 1
  • 17
  • 22
  • Thanks, this seems to somehow work, although every time the IsFooUnique method is called the parameter Foo is always null, any idea why? – kulhajs Mar 12 '15 at 11:59
  • Check your page to see if you have an input with the name `Foo` (the same as the parameter). It's possible that you have a prefix like `Model.Foo`. In this case you should either add [Bind(Prefix = "Model.Foo")] to the Foo parameter of the IsFooUnique action or update the action to `public JsonResult IsFooUnique(Model model)` and check using `model.Foo` and `model.ID`. – SmartDev Mar 12 '15 at 12:18