1

I have an employee class in model for ASP.NET MVC3. There is a field named “EmpName”. There is a create action for creating employee records. There should be a server side validation that - the second letter of the name should be “E” and third letter of the name should be “F”. (There is no client side validation). If the validation is failed, the message should be displayed in the create view as a validation summary. How do we do this?

Note: Validation errors for these two validations is expected to come as two error result (two different line).

Note: I am not using Entity Framework

Following is the view code.

@model MyApp.Employee
@{  ViewBag.Title = "Create";  }   
<h2>Create</h2>    
@using (Html.BeginForm()) 
{    
    <div >          EmpName :~: @Html.EditorFor(model => model.EmpName)  </div>      

CONTROLLER

// GET:       
public ActionResult Create()      
{                      
   return View();      
}

// POST:
[HttpPost]      
public ActionResult Create(Employee emp)      
{          
if (ModelState.IsValid)          
{             
 //Save the employee in DB first and then redirectToAction.
            return RedirectToAction("Index");          
    }
}

READING:

  1. ASP.NET MVC3: ValidationType ModelClientValidationRule

  2. How does DataAnnotations really work in MVC?

  3. ASP.NET MVC 3 client-side validation with parameters

  4. http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html

  5. Add Sorting and Searching in Contact Management ASP.NET MVC Application

  6. http://trainingkit.webcamps.ms/AspNetMvc.htm

  7. ValidationSummary and ValidationMessageFor with custom CSS shown when no errors present

  8. http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-1

  9. What is the better ASP.NET MVC 3.0 Custom Validation approach

  10. http://dotnetslackers.com/articles/aspnet/Validating-Data-in-ASP-NET-MVC-Applications.aspx

Community
  • 1
  • 1
LCJ
  • 22,196
  • 67
  • 260
  • 418
  • Are you using any ORM that creates entities for you? or you have created your own POCOs? – Amir Feb 19 '12 at 06:10
  • I am just learning MVC. I used Employee object that I created in controller page. A similar approach I have posted in another question. Please refer http://stackoverflow.com/questions/9340093/asp-net-mvc3-object-from-dropdownlist-in-null-in-controller . Also, in real sceanrio, I will be getting database values using a WCF calls. I am planning to call WCF services directly from controller. Is that good approach? – LCJ Feb 19 '12 at 06:12
  • Is the approach mentioned in the following suitable here? http://stackoverflow.com/questions/9349766/asp-net-mvc3-validationtype-modelclientvalidationrule. – LCJ Feb 19 '12 at 14:37

2 Answers2

2

You can add server side errors using ModelState.AddModelError. When the ModelState contains errors it will result in ModelState.IsValid being false.

[HttpPost]      
public ActionResult Create(Employee emp)      
{         
if (YourServerValidation(emp) == false) 
{
    ModelState.AddModelError("EmpName", "Invalid value");
}

if (ModelState.IsValid)          
{             
    //Save the employee in DB first and then redirectToAction.
    return RedirectToAction("Index");          
}
else
{ 
    return View(emp);
}

Your view should be updated as follows:

<div>
    EmpName :~: @Html.TextBoxFor(model => model.EmpName)
    @Html.ValidationMessageFor(model => model.EmpName)
</div>
Philip Fourie
  • 111,587
  • 10
  • 63
  • 83
  • I have upvoted your suggestion. Howver, is the approach mentioned in the following suitable here? http://stackoverflow.com/questions/9349766/asp-net-mvc3-validationtype-modelclientvalidationrule. – LCJ Feb 19 '12 at 14:37
2

Your model can implement the IValidatableObject(inside System.ComponentModel.DataAnnotations namespace)

Your model should be something like below:

public class Employee : IValidatableObject
{

    public string EmployeeName;


    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        char secondNameChar = EmployeeName[1];
        char thirdNameChar = EmployeeName[2];

        if (secondNameChar.ToString().ToLower() != "e")
            yield return
                new ValidationResult("Second char of name should be 'E'",
                                     new[] {"EmployeeName"});
        if (thirdNameChar.ToString().ToLower() != "f")
            yield return
                new ValidationResult("Third char of name should be 'F'",
                                     new[] {"EmployeeName"});


    }
}

Please note that add other properties of the employee to this class, and do your validation inside Validate method.

And now on the controller if you call ModelState.IsValid on an invalid object, this fails and return two errors and show them both to the user.

Amir
  • 9,577
  • 11
  • 41
  • 58
  • I have upvoted your suggestion. Howver, is the approach mentioned in the following suitable here? http://stackoverflow.com/questions/9349766/asp-net-mvc3-validationtype-modelclientvalidationrule. – LCJ Feb 19 '12 at 14:37
  • You may use self validation (implementing IValidatableObject) where ever you have your entities. You can use this approach on your entities within a WCF service as well(to validate your Data Contracts). – Amir Feb 19 '12 at 23:24