leora
leora

Reputation: 196821

asp.net-mvc textbox validation

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

such as:

how would i go about doing this?

Upvotes: 1

Views: 2366

Answers (1)

Thomas Stock
Thomas Stock

Reputation: 11296

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

Upvotes: 6

Related Questions