Vara Prasad.M
Vara Prasad.M

Reputation: 1550

How to pass the custom error message for data annotation property

If i have a data contracts in separate project and i will use the data contract in the website. And now i want to give the custom error message for the data member.

How can i achieve this in the C#, ASP.Net

for example:

[DataMember]
[Required]
public string City { get; set; }

How can i give the customized message - ErrorMessage = "City is required." for the data contract?

Upvotes: 1

Views: 2193

Answers (2)

Ahmad Hamdy Hamdeen
Ahmad Hamdy Hamdeen

Reputation: 556

public class Product 
{
     [NotMapped] // <--
     public const string priceStartsAt = "price starts at $5.00"; // <--
                
     [Key]
     public int Id { get; set; }
     [Required]
     public string Name { get; set; }
     [Required]
     [Range(5, 10000, ErrorMessage = priceStartsAt)] // <--
     public string FullDescription { get; set; }
     [Required]
     [Column(TypeName = "decimal(18,2)")]
     [Range(5, 10000, ErrorMessage = priceStartsAt)] // <--
     public decimal VendorPrice { get; set; }
     [Required]
     [Column(TypeName = "decimal(18,2)")]
     [Range(5, 10000, ErrorMessage = priceStartsAt)] // <--
     public decimal CustomerPrice { get; set; }  
     [Column(TypeName = "decimal(18,2)")]
     [Range(5, 10000, ErrorMessage = priceStartsAt)] // <--
     public decimal OldCustomerPrice { get; set; }
}

Upvotes: 0

Kek
Kek

Reputation: 3195

You could pass it in the validationAttribute:

public class MyClass
{
    [Required(ErrorMessage="your custom message here")]
    public object MyProperty { get; set; }
}

Upvotes: 2

Related Questions