Translator’s Note: Why are foreigners so good at talking about mountains and rivers? He is so verbose that he can dig out three bedrooms and two living rooms with his feet…
In terms of verification, which one is better, Fluent Validation or Data Annotations? This question is often asked by developers, and this article will briefly answer it.
What is smooth verification
Before discussing Fluent Validation in depth, it is necessary to understand the origin and capabilities of Fluent Validation.
Introduction
Fluent Validation is a strong-type verification rule base built on a fluent interface (the author likens it to a spaceship searching to avoid an asteroid). It is a method favored by geeks. For example, to verify object members:
public class CustomerValidator: AbstractValidator<Customer> { publicCustomerValidator() { RuleFor(customer => customer.Name).NotEmpty(); // Ensure the customer name is not an empty string RuleFor(customer => customer.Age).InclusiveBetween(18, 60); // Ensure the customer age falls between 18 and 60 } }
The above example demonstrates the use of Fluent Validation to set basic rules for the Customer
entity. Each rule is clearly identifiable and can be understood by engineers at a glance.
Benefits
There are the following points:
-
customizable
-
Allow complex validation rules
-
Can be integrated with ASP.NET
Common scenarios
Sometimes you need to perform complex validation on a single attribute (such as validating a Customer who is 18 years old or older and has a valid insurance policy), in which case Fluent Validation is suitable:
public class CustomerValidator: AbstractValidator<Customer> { publicCustomerValidator() { RuleFor(customer => customer.HasInsurancePolicy).Equal(true); RuleFor(customer => customer.Age).GreaterThanOrEqualTo(18); } }
What is data annotation
Data Annotations are completely different from Fluent Validation.
A brief introduction to data annotation
Essentially, Data Annotations are attributes that can be placed in a domain model to indicate its behavior, making it a “guide” to the code and making it more readable. In addition to the organization of the code, data annotations are more transparent and easily identifiable, simplifying debugging. For example, use simple data annotations for validation in the Customer class:
public class Customer { [Required(ErrorMessage = "Customer Name is required")] public string Name { get; set; } [Range(18, 60, ErrorMessage = "Age should be between 18 and 60")] public int Age { get; set; } }
This code shows how to apply validation rules directly to the properties Name and Age through Data Annotations. Each annotation is directly adjacent to the property it validates, making the code much more readable.
Advantages of data annotation
Data Annotations have the following three advantages:
-
Statement on the spot: Make the model clear at a glance
-
Simplicity: no additional validation classes are introduced, just validation rules are attached to the class
-
Seamless: perfectly embedded into ASP.NET MVC
Advanced usage of data annotations
Data annotations can not only perform simple checks on fields, but can also be combined with ORM tools to check the uniqueness of data:
public class UniqueEmailAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var _context = (DatabaseContext)validationContext.GetService(typeof(DatabaseContext)); var entity = _context.Users.SingleOrDefault(e => e.Email == value.ToString()); if (entity != null) { return new ValidationResult(GetErrorMessage()); } return ValidationResult.Success; } public string GetErrorMessage() { return "Email address must be unique"; } } public classCustomer { [Required(ErrorMessage = "Email Address is required")] [EmailAddress(ErrorMessage = "Invalid Email Address")] [UniqueEmail] public string Email { get; set; } }
Use cases of data annotation
In order to ensure that the data entered by customers is accurate (error-free), the e-commerce platform uses data annotations to perform input verification on the model:
public class Product { [Required] [StringLength(100)] public string Title { get; set; } [Range(0.01, 1000)] public decimal Price { get; set; } }
Data annotations act on the Product
class to ensure that Title
is not empty and has a maximum length of 100 characters, and that Price
is within the specified range.
Educational applications will face the problem of complex interactions between teachers and students, and data annotation can meet these requirements (I don’t know what the author thinks), as follows:
public class Student { [Required] [StringLength(50)] public string FirstName { get; set; } [Required] [StringLength(50)] public string LastName { get; set; } [Required] [DataType(DataType.Date)] public DateTime DateOfBirth { get; set; } [Required] [UniqueStudentID] public int StudentID { get; set; } }
In this model, data annotation once again comes into play to ensure data integrity. Note how they verify that FirstName
and LastName
are provided and adhere to the set character limits; also, DateOfBirth
must be a valid date, And each StudentID
should be unique.
Data Annotations Data Annotations go beyond the ordinary and bring extraordinary precision where the sword of C# falls.
Compare
There will always be a battle between Fluent Validation and Data Annotations, and victory will be won by coincidence.
Difference
Fluent validation has the same purpose as data annotation, but is used in completely different ways.
Code Organization
Code organization aspects. Fluent validation requires a separate class for validation, whereas data annotations are more cohesive, placing validation attributes directly within the class. Take age verification as an example:
Using Fluent Validation, we do this:
public class CustomerValidator: AbstractValidator<Customer> { publicCustomerValidator() { RuleFor(customer => customer.Age).GreaterThanOrEqualTo(18).WithMessage("Customer must be at least 18 years old"); } }
Using Data Annotations, we do:
public class Customer { [Required] [Range(18, Int32.MaxValue, ErrorMessage = "Customer must be at least 18 years old")] public int Age { get; set; } }
This shows the difference in code organization between the two.
Complexity Handling
Complexity handling aspects. Smooth verification is mostly used in complex scenarios and advanced verification applications, while in other relatively simple scenarios that don’t require complexity, data annotations are mostly used.
To verify that a customer is over 18 and has insurance, using Fluent Validation, we do this:
public class CustomerValidator: AbstractValidator<Customer> { publicCustomerValidator() { RuleFor(customer => customer.HasInsurancePolicy).Equal(true); RuleFor(customer => customer.Age).GreaterThanOrEqualTo(18); } }
Although the same capabilities can be achieved through data annotation, it is more complex.
Customizability
In terms of customizability. The two perform differently in this regard. Fluent Validation is better in terms of complex validation and customization, while Data Annotations is slightly less popular, but it has a lower threshold.
Below is an overview of their differences
Standard | Fluent verification | Data annotation |
---|---|---|
Code Organization | Use a separate validation class | Implement within the class |
Complexity Handling | Suitable for complex scenarios | Suitable for simple, attribute-based verification |
Customizability | Highly customizable (custom verification provided) | Low customizable (limited to provided properties) |
Complexity comparison: ease of use vs. flexibility
As the ancients said, Regard your code as your castle. We must decide the winner (the translator said that the second grade was not helpful in understanding this paragraph).
Smooth verification
A veteran on the battlefield, good at dealing with difficult and complicated diseases:
public class CustomerValidator: AbstractValidator<Customer> { publicCustomerValidator() { RuleFor(customer => customer.Name).NotNull().WithMessage("Customer name cannot be null or empty"); RuleFor(customer => customer.HasInsurancePolicy).Equal(true).WithMessage("Customer must own an insurance policy"); RuleFor(customer => customer.Age).GreaterThanOrEqualTo(18).WithMessage("Customer must be at least 18 years old"); } }
Data annotation
A knight’s loyal dog, a personal guard.
Compare the ease of use and flexibility of the two:
Standard | Fluent verification | Data annotation |
---|---|---|
Easy to use | Medium (functionality requires understanding the complexity of multiple classes) | Low (easy to apply built-in properties) |
Flexibility | High (allows creation of complex validation rules) | Low (limited to provided built-in properties) |
Customizability | High (powerful API for custom rules and messages) | Low (limited customization options) |
Code reusability | High (reusable validation classes) | Low (annotations are model-related, so reusability is low) |
Cross-layer applicability | High (independent of the data model. Can be used in different layers) | Low (usually related to the data model) |
Performance analysis: Which one is faster?
It’s time to fight with bayonets again. Fluent Validation and Data Annotations once again took out their bayonets. Which one is faster?
Although the fluency verification is flexible, the action is slightly slower than the data annotation. The outcome of the battlefield competition is fleeting, and the winner has not yet been determined!
The data annotation speed is slightly faster, and every inch is short and every inch is risky! But in applications, this performance gain can be small and won’t have a significant impact on most applications.
Comparing results:
Standard | Fluent verification | Data annotation |
---|---|---|
Performance | Slower due to complex validation processing | Faster due to simple attribute matching |
Apply Scenarios | Ideal for complex, custom and multi-layer verification | Ideal for simple single-layer verification scenarios |
Testability | High (validation logic can be tested separately) | Medium (involving testing models and validation rules together) |
Integrated with ORM | Lower (requires separate validation call) | Higher (integrated with Entity Framework by default) |
Remember, speed is not the key to victory or defeat, the scene is! For complex scenes, leave it to professional veterans; for simple scenes, trust your loyal dog!
Practical application and practice
Developers often gravitate toward hands-on examples of technology applications, and theory alone may not be enough to solve many problems. Next, we will delve into the application scenarios to actually experience the similarities and differences between smooth verification and data annotation.
Build software solutions using fluent verification
You might be surprised at how commonly used Fluent Validation is in the software solutions you use every day:
E-commerce platform
Fluent Validation plays a huge role in the smooth functioning of your online shopping system. Consider a shopping cart function with different input fields. Let’s take the coupon code function as an example:
public class CouponValidator : AbstractValidator<Coupon> { publicCouponValidator() { RuleFor(coupon => coupon.Code).NotEmpty().WithMessage("Coupon code is required."); RuleFor(coupon => coupon.Discount).GreaterThan(0).WithMessage("Discount should be greater than zero."); } }
In this code, the e-commerce application verifies that the coupon code entered by the user is not empty and that the discount associated with it is greater than zero.
Financial system
For financial systems such as investment applications, smooth verification is crucial. A good example of this is when users set price alerts for specific stocks.
public class PriceAlertValidator : AbstractValidator<PriceAlert> { public PriceAlertValidator() { RuleFor(alert => alert.Stock).NotNull().WithMessage("A stock is required for setting a price alert."); RuleFor(alert => alert.ThresholdPrice).GreaterThan(0).WithMessage("The threshold price must be greater than zero."); } }
In this code snippet, the financial application ensures that when setting price alerts a stock is mentioned and the alert price is greater than zero.
Successful cases of using data annotations
Likewise, data annotation has been used in various fields:
CMS
Let’s say you’re building a blogging system; it’s crucial to make sure your blog post URLs are unique and correct. In this case, you can use data annotations.
public class BlogPost { [Required, MaxLength(150)] public string Title { get; set; } [Required] [RegularExpression(@"^(?:([\w\d\s-] + )=(?:http|https)://([\w\d-] + )\.([\w\d \.] + )/([\w\d-] + ))$", ErrorMessage = "Please enter a valid URL.")] public string URL { get; set; } }
In this code, the data annotation verifies that the URL entered when creating a new blog post is valid and that the title provided is not empty or longer than 150 characters.
Ticketing system
When booking a flight online, it is important to fill in all the fields correctly. Let’s consider booking form validation.
public class TicketBooking { [Required] public string Name { get; set; } [Required, RegularExpression(@"^[a-zA-Z0-9._% + -] + @[a-zA-Z0-9.-] + \.[a-zA-Z]{2,}$ ")] public string Email { get; set; } [Required, Range(1, 10)] public int Quantity { get; set; } }
Here, the data annotation ensures that the name and email fields are filled in, and that the number of tickets ranges from 1 to 10.
So whether it’s streaming validation or data annotation, each service has practical value in the real world, and the choice between them often depends on your specific requirements and preferences.
Case closed: Which is better?
Here we go again, which one is better? Hard to choose.
This section provides a comprehensive comparison, considering factors such as project complexity, ease of use, flexibility, and performance. The purpose is to guide you in making informed decisions.
Notes
Key aspects to consider include:
Project complexity
The size and complexity of the project are critical in choosing the right validation framework. Is your project large-scale and with complex validation requirements, or simple and does not require complex validation?
Factors | Fluent validation | Data annotation |
---|---|---|
Simple | ? Needed | ? Simple attribute-based method |
Complex scenarios | ? Support complex authentication scenarios | ? Limited support for advanced authentication requirements |
Ease of use and flexibility
Consider the learning curve and flexibility provided by the verification method. Do you prefer precise control over validation rules, or is a simple solution suitable for you?
Factors | Fluent validation | Data annotation |
---|---|---|
Easy to use | ? Steeper learning curve | ? Easier to implement, less coding involved |
Flexible Performance | ? High flexibility, custom validation rules | ? Low flexibility, standard validation rules |
Performance impact
Consider the impact on performance. Small delays can become a significant problem, especially in large-scale data-intensive projects.
Factors | Fluent validation | Data annotation |
---|---|---|
Performance | ? Typically performs better | ? May introduce latency in big data applications |
Applicability
Applicability: Choose the right verification solution for your project
Understanding your project’s requirements will guide your decision:
-
For less complex, attribute-based projects, data annotation may be more appropriate.
-
Choose Fluent Validation to handle complex custom rules.
Looking back: Which one is better?
Ultimately, the choice wasn’t clear. A lot depends on the unique requirements of your project.
If you have a simple project without complex validation rules, the ease and speed of implementing data annotation may be your best option.
However, if you are working on a project with custom validation rules or complex requirements, the flexibility and control provided by Fluent Validation can be very beneficial.
Remember, the best solutions strike a balance between meeting specific project needs, ensuring data validity, and maintaining code efficiency.
Summary
Dear reader (Translator: You have read this, and I admire your patience), now comes the critical moment of choice.
Understand the overall situation of verification requirements
Apply a simple formula: Project Requirements + Validation Needs = Best Validation Technique
.
Final Thoughts: Ensuring Quality and Efficiency in C# Coding Practices
Remember, folks, validation is your line of defense against messy data trying to invade your beautiful codebase! Whether it’s fluent validation or data annotation, choose your technology wisely and maintain the sanctity of your C# code.
Dear C# veteran drivers, please drive your tutuk cars in a handsome way. May smooth verification or data annotation be with you.
(There is so much nonsense from foreigners…)
Original text: https://www.bytehide.com/blog/fluent-validation-vs-data-annotations-csharp
Author: Juan Espa?a
Donations are welcome
Your donation will go towards community initiatives