Custom Validation Attribute Asp.net Core 2019

SAGAR JAYBHAY
3 min readDec 11, 2019

--

How to Create Custom Validation Attrbute Asp.Net Core?

Built-in Validation Attribute

  1. Required
  2. Range
  3. StringLength
  4. RegularExpression
  5. Compare
  6. Etc..

When in your project we have some requirements that can not be full fill with some in-built validation attributes then we need to create some Custom validation attribute. In this, we have created one CustomValidator class which inherits from ValidationAttribute inbuilt class. After inheriting from this we need to override the IsValid method.

Nowin our example, we have to achieve the functionality of we are valid for only Gmaildomain mail-id. Other than Gmail we restrict the user for creating an account.

After creating this CustomValidator attribute you can use this as our normal attributes.

Custom Validation Attribute Class in Asp.net core

Now we are adding code for this validation

public class CustomValidator:ValidationAttribute
{
private string allowedDomain { get; set; }
public CustomValidator(string allowedDomain)
{
this.allowedDomain = allowedDomain;
}
public override bool IsValid(object value)
{
string[] array = value.ToString().Split("@");
if (array.Length > 1)
return array[1].ToLower() == allowedDomain.ToLower();
else
{
return false;
}
}
}

In this code, we have created one property allowed domain which isfor we pass the domain name from our CustomValidator as a parameter.

See below code

public class RegistrationVIewModel
{

[Required]
[EmailAddress]
[Remote(controller:"Account",action: "IsUsedEmailID")]
[CustomValidator(allowedDomain:"gmail.com",
ErrorMessage = "Email Domain Must Be gmail.com")]
public string Email { get; set; }

[Required]
[DataType(DataType.Password)]
public string Password { get; set; }


[Required]
[DataType(DataType.Password)]
[Display(Name = "Confirm Password")]
[Compare("Password",ErrorMessage = "Password and Confirm Password not match.")]
public string ConfirmPassword { get; set; }
}

Now see the image

Custom Validation Attribute Declaration in asp.net core

Here we pass that parameter for that reason we need to createproperty and constructor in this class and need to catch this.

In this we have split the email id with the use of @ symbol thenwe check first array length greater than 1 and then we check with email iddomain name.

See the below output

Here we pass that parameter for that reason we need to createproperty and constructor in this class and need to catch this.

In this we have split the email id with the use of @ symbol thenwe check first array length greater than 1 and then we check with email iddomain name.

See the below output

GitHub Project Link: https://github.com/Sagar-Jaybhay/LearnAspNetCore

Originally published at https://sagarjaybhay.com on December 11, 2019.

--

--

SAGAR JAYBHAY

A software developer, trainer, trader and enthusiastic learner.