tags:

views:

247

answers:

1

i am using the sample asp.net mvc app and i want to add specific validation on certain textboxes

such as:

  • No spaces
  • Min / Max size

how would i go about doing this?

+3  A: 

An example:

Controller:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(Company company)
{
    //validate and save data
    if (ValidateCompanyData(company))
    {
        _service.SaveCompanyData(CustomerId, company);
        ViewData["info"] = "Your changes have been saved.";
    }

    var companyViewData = GenerateCompanyViewData(company);

    return View("Index", companyViewData);
}


[NonAction]
public bool ValidateCompanyData(Company company)
{
    if (!company.VAT.HasValue())
    {
        ModelState.AddModelError("VAT", "'Vat' is a required field.");
    }
    if (!company.CompanyName.HasValue())
    {
        ModelState.AddModelError("CompanyName", "'Name' is a required field.");
    }

    return ModelState.IsValid;
}

View:

Html.ValidationMessage("VAT")

To access the errormessage.

In case you're wondering: .HasValue() is an extension method that is the same as !string.IsNullorEmpty()

Thomas Stock