Search code examples
c#asp.net-mvcemail-validationmodel-validation

Email Validation in .Net mvc4


Currently I am using following code for email validation but it does validate the dsgf@g mail id please help me

[Required(ErrorMessage = "Please Enter Email Id")]
[Display(Name = "Email-Id")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Cust_Email { get; set; }

Solution

  • EmailAddress attribute will mark as valid the dsgf@g because it is a completely valid email address, so there is nothing wrong with that method. Consider the example username@localhost for example.

    If it is not suits you then you can use regular expression ti set your own rule for validation. Try to use 'RegularExpression' attribute instead, something like:

    [RegularExpression("^[^@\s]+@[^@\s]+(\.[^@\s]+)+$", ErrorMessage = "Invalid Email Address")]
    public string Cust_Email { get; set; }
    

    or

    [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage = "Invalid Email Address")]
    public string Cust_Email { get; set; }