Search code examples
c#jsonapiazure-functionsfluentvalidation

How to Validate a list of JSON Objects using Fluent Validation and Azure Function in C#?


I am trying to validate a list of JSON objects using Fluent Validation. I referred the official documentation https://docs.fluentvalidation.net/en/latest/collections.html as well but my function is not able to validate list of json objects

public class MyModel
    {
        public string _No { get; set; }
        public string _date { get; set; }
        public string expiry_date { get; set; }
        public string I_Name { get; set; }
}

public class MyModels
    {
        public List<MyModel> mymodel { get; set; } = new List<MyModel>();
            
    }



public class ModelValidator : AbstractValidator<MyModel>
    {
        public ModelValidator()
        {
            RuleFor(x => x._No).NotEmpty();
            RuleFor(x => x._date).NotEmpty();
        }
}


public class MyModelsValidator : AbstractValidator<MyModels>
    {  
       public ModelsValidator()  
        {
             RuleForEach(x => x.mymodel).SetValidator(new ModelValidator()); 
        }
    } 

main.cs

 public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)

Validators.MyModelsValidator val = new MyModelsValidator();

string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

var p = JsonConvert.DeserializeObject<MyModels>(requestBody);

var results = await val.ValidateAsync(p);

The result is that it is not validating and I returned the value of p is returned as null. I am not sure how to handle list of JSON objects with Fluent Validation.

My JSON string is of format:

{
"Data":[
    {
"_No":"12345678"
,"_date":"2022-02-08"
,"_expiry_date": "2023-02-08"
, "I_Name" : "Sam"
},

{
"_No":"5587421"
,"_date":"2022-02-10"
,"_expiry_date": "2024-02-08"
, "I_Name" : "Tam"
}

]
}

Can anyone please help me and suggest what I am doing wrong here?


Solution

  • Please follow the below workaround to fix your issue:

    I am slightly modified your code for my better understanding.

    MyModel.cs class

     public class MyModel
        {
            public string _No { get; set; }
            public string _date { get; set; }
            public string _expiry_date { get; set; }
            public string I_Name { get; set; }
        }
    
        public class RootModels
        {
            public List<MyModel> data { get; set; }
        }
    
        public class ModelValidator : AbstractValidator<MyModel>
        {
            public ModelValidator()
            {
                RuleFor(x => x._No).NotEmpty();
                RuleFor(x => x._date).NotEmpty();
                RuleFor(x => x._expiry_date).NotEmpty();
                RuleFor(x => x.I_Name).NotEmpty();
            }
        }
    
        public class MyModelsValidator : AbstractValidator<RootModels>
        {
            public MyModelsValidator()
            {
                RuleForEach(x => x.data).NotNull().SetValidator(new ModelValidator());
            }
        }
    

    Function.cs

     public static async Task<IActionResult> Run(
                [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,ILogger log)
            {
                MyModelsValidator val = new MyModelsValidator();
                //Reading Request Body from post request
                string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                //Deserializeing Json Object
                var p = JsonConvert.DeserializeObject<RootModels>(requestBody);
                //Validating the Json Object
                var results = await val.ValidateAsync(p);
                //Check the result is valid or not
                if(results.IsValid == true)
                {
                    log.LogInformation("The json object is valid");
                }
                log.LogInformation($"jsonvalue: {p.data[1].I_Name},.....");
                ...
            }
    

    Post Request Body Data

    {
    "Data":[
        {
            "_No":"12345678",
            "_date":"2022-02-08",
            "_expiry_date": "2023-02-08",
            "I_Name" : "Sam"
        },
        {
            "_No":"5587421",
            "_date":"2022-02-10",
            "_expiry_date": "2024-02-08",
            "I_Name" : "Tam"
        }
        ]
    }
    

    Make sure you have used valid JSON data while post Request like above.

    I saw your JSON Data while post Request it has a different format like below. (Avoid the incorrect format of json)

    "_No":"12345678"
    ,"_date":"2022-02-08"
    ,"_expiry_date": "2023-02-08"
    , "I_Name" : "Sam"
    },
    

    Results:

    enter image description here

    enter image description here