JuliethB
JuliethB

Reputation: 21

How to implement FluentValidation in a c# project

Regards

I am quite new in the implementation of FluentValidation in my projects of .Net and I am with a simple example of validating a variable and executing its result but I can not find the way to execute said result by console. I have only found examples in aspnet MCV which does not help me because the application I am developing is not a web. If someone can help me, I really appreciate it.

I have this example:

ConfigData.cs

[Validator(typeof(EntityValidator))]
public class ConfigData {
public string EntityName { get; set; }
}

EntityValidator.cs

public class EntityValidator : AbstractValidator<ConfigData>{
public EntityValidator(){
RuleFor(x => x.EntityName).NotNull().WithMessage("ERROR! The field can not be empty");
}

ConfigData cd = new ConfigData();
EntityValidator ev = new EntityValidator();
ValidationResult result = validator.Validate(cd);
}

I do not know what else would be missing, I do not know how to execute this code in the Program.cs of my project. I appreciate the help very much.

Upvotes: 0

Views: 1134

Answers (1)

Sergey Prosin
Sergey Prosin

Reputation: 711

The code below works

public static void Main()
{
   ConfigData cd = new ConfigData();
   EntityValidator ev = new EntityValidator();
   ValidationResult result = ev.Validate(cd);

   Console.WriteLine(result.IsValid);
   foreach (var error in result.Errors)
       Console.WriteLine(error.ErrorMessage);

   Console.ReadLine();
}

The result is

False
ERROR! The field can not be empty

Upvotes: 2

Related Questions