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?

1 Answer 1

6

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()

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.