Error messages for model validation using data annotations

Posted by oneBelizean on Stack Overflow See other posts from Stack Overflow or by oneBelizean
Published on 2010-05-11T19:52:14Z Indexed on 2010/05/11 19:54 UTC
Read the original article Hit count: 301

Given the follow classes:

using System.ComponentModel.DataAnnotations;

public class Book{
   public Contact PrimaryContact{get; set;}
   public Contact SecondaryContact{get; set;}

   [Required(ErrorMessage="Book name is required")]
   public string Name{get; set;}
}
public class Contact{
    [Required(ErrorMessage="Name is required")]
    public string Name{get; set;}
}

Is there a clean way I can give a distinct error message for each instance of Contact in Book using DataAnnotations? For example, if the name was missing from the PrimaryContact instance the error would read "primary contact name is required".

My current solution is to create a validation service that checks the model state for field errors then remove said errors and add them back using the specific language I'd like.

© Stack Overflow or respective owner

Related posts about dataannotations

Related posts about c#