Open Closed

how to Create custom validation attribute mvc core ? #9271


User avatar
0
devmahmod created

i have this dto in contract project

public class CreateNewsDto
 {
      [Required(ErrorMessage = "The {0} field is required")]
      [StringLength(200, ErrorMessage = "The {0} must not exceed {1} characters")]
      public string TitleAr { get; set; }

      [Required(ErrorMessage = "The {0} field is required")]
      [StringLength(200, ErrorMessage = "The {0} must not exceed {1} characters")]
      public string TitleEn { get; set; }

      [Required(ErrorMessage = "The {0} field is required")]
      [StringLength(500, ErrorMessage = "The {0} must not exceed {1} characters")]
      public string DescriptionAr { get; set; }

      [Required(ErrorMessage = "The {0} field is required")]
      [StringLength(500, ErrorMessage = "The {0} must not exceed {1} characters")]
      public string DescriptionEn { get; set; }

      [Required(ErrorMessage = "The {0} field is required")]
      [DataType(DataType.Date)]
      public DateTime PublishDate { get; set; }

      //[Required(ErrorMessage = "The {0} field is required")]
      //public IFormFile? Image { get; set; }
  }

I want to make custom validation attribute ImageOnly how to implement in mulit layer project mvc core


3 Answer(s)
  • User Avatar
    0
    EngincanV created
    Support Team .NET Developer

    Hi, it's the same as how to create it on the .NET side. You need to create an attribute that inherits from ValidationAttribute and implement the IsValid method:

    [AttributeUsage(AttributeTargets.Property)] //only can be used in properties
    public class YourCustomAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            //implement
        }
    }
    

    Then use the attribute on top of your property or class:

    public class CreateNewsDto
     {
          [Required(ErrorMessage = "The {0} field is required")]
          [StringLength(200, ErrorMessage = "The {0} must not exceed {1} characters")]
          [YourCustom] //your attribute
          public string TitleAr { get; set; }
          
          //...      
    }
    

    Since this is not related to ABP, you can refer to https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/reflection-and-attributes/ for further info.

    Regards.

  • User Avatar
    0
    devmahmod created

    Which project can i implement YourCustomAttribute and also note that my Attribute will ensure that it is really image file not pdf and user just changed extension so i mean it is logic that's why i ask you which project will implement this attribute to put in mt dto which in contract project ?

  • User Avatar
    0
    EngincanV created
    Support Team .NET Developer

    Which project can i implement YourCustomAttribute and also note that my Attribute will ensure that it is really image file not pdf and user just changed extension so i mean it is logic that's why i ask you which project will implement this attribute to put in mt dto which in contract project ?

    Hi, yes you can create and define your attribute in the *.Application.Contracts project. You should basically create an attribute, inherit it from the ValidationAttribute base class of .NET, then override the IsValid method and apply your own logic.

    Btw, in one of my old project, I had similar requirements and created an AllowedExtensionsAttribute as follows:

    public class AllowedExtensionsAttribute : ValidationAttribute
        {
            private readonly string[] _extensions;
            public AllowedExtensionsAttribute(string[] extensions)
            {
                _extensions = extensions;
            }
    
            protected override ValidationResult IsValid(
                object value, ValidationContext validationContext)
            {
                if (value == null)
                {
                    return ValidationResult.Success;
                }
                
                var file = value as IFormFile;
                var extension = Path.GetExtension(file.FileName);
                
                if (file.Length > 0 && file != null)
                {
                    if (!_extensions.Contains(extension.ToLower()))
                    {
                        return new ValidationResult(GetErrorMessage());
                    }
                }
    
                return ValidationResult.Success;
            }
    
            public string GetErrorMessage()
            {
                return $"This extension is not allowed!";
            }
        }
    

    and use the attribute:

    [AllowedExtensions(new string[] { ".jpg", ".png", ".jpeg" })]
    public IFormFile CoverImageFile { get; set; }
    

    Since this is not related to ABP, you can refer to https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/reflection-and-attributes/ for further info.

Boost Your Development
ABP Live Training
Packages
See Trainings
Mastering ABP Framework Book
The Official Guide
Mastering
ABP Framework
Learn More
Mastering ABP Framework Book
Made with ❤️ on ABP v9.3.0-preview. Updated on May 14, 2025, 07:53