Search code examples
c#.netvalidationdata-annotations

Disable data annotation for specific DTO


I would like to disable data annotation validation for some case. You assume that we have two DTO and two endpoint

public class CreateBulkProductDto 
{
        [Required]
        public List<CreateProductDto> Products { get; set; }
 }

public class CreateProductDto {
    [Required]
    [StringLength(100)]
    public string Name { get; set; }
    [Required]
    public List<CreateProductCategoryDto> Categories { get; set; }
    [Required]
    public List<string> Barcodes { get; set; }

}

Endpoints;

public virtual async Task<List<CreateOrUpdateBulkProductResultDto>> CreateBulkAsync(CreateBulkProductDto input){.....}
public virtual async Task<string> CreateAsync(CreateProductDto input){....} 

When the request comes to CreateBulkAsync, I want to disable validations, but when the request comes to CreateAsync, I want validations to work. How can I solve this problem


Solution

  • I have written an extension method for this. It currently only works on a single key value. But I imagine you are able to extend on this yourself.

    This code will only work if you explicitly check the ModelState.IsValid.

    If (!ModelState.IsValid) { return; }
    

    Make sure you do not over use this, since skipping your validation isn't recommended by any means.

    public static bool MarkFieldsValid(this ModelStateDictionary modelState, string key)
    {
        if (string.IsNullOrWhitespace(key)) { return false; }
        
        var modelStates = modelState.FindKeysWithPrefix(key);
    
        foreach (var state in modelStates)
        {
            modelState.ClearValidationState(state.Key);
            modelState.MarkFieldValid(state.Key);
        }
    
        return true;
    }
    

    Then you could implement it like this:

    ModelState.MarkFieldsValid("key");
    
    If (!ModelState.IsValid) { return; }