Sunday, May 12, 2019

Customize Validation error message in ASP.NET Core MVC

In the previous post we saw on how to implement field level validations by adding validation attributes to the Model class. We saw that the validation messages were auto generated based on the validation rules, we might want to add custom validation messages, we can do this by adding an ErrorMessage property to the validation attributes.

In the sample below we will add custom error messages using the ErrorMessage property and see how this is reflected in the View.

public partial class Users
{
    public int UserId { get; set; }
    [StringLength(50)]
    [Required(ErrorMessage = "Please enter First Name.")]
    public string FirstName { get; set; }
    [StringLength(50)]
    [Required]
    public string LastName { get; set; }
    [StringLength(10)]
    [RegularExpression(@"^[0-9]{10}",
        ErrorMessage ="Phone Number should contain only Numbers.")]
    [Required]
    public string Phone { get; set; }
    [RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",
        ErrorMessage = "Please enter a valid Email address."),
        Required,
        StringLength(50)]
    public string Email { get; set; }
    [Required, StringLength(100)]
    public string Address { get; set; }
    public string AttachmentPath { get; set; }
}





Search Flipkart Products:
Flipkart.com

No comments: