Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Ravi Vishwakarma
Ravi Vishwakarma

Posted on

     

Global Class Validator for Enhanced Object Validation in EMS

Introducing Global Class Validator: Streamlined Object Validation for Employee Management Systems

Validation is a critical aspect of any application that handles structured data. To ensure accuracy, consistency, and compliance with business logic, validation must be seamless and reliable.

Our Global Class Validator is a powerful utility tailored for .NET applications, particularly useful in systems like the Employee Management System. It simplifies object validation by leveraging .NET’s built-inValidationAttributeand ensures that your data meets defined standards effortlessly.

Key Features

  1. Thread-Safe Error Tracking: Errors are captured and stored in a thread-safe manner, ensuring accurate results even in multi-threaded environments.
  2. Dynamic Property Validation: The validator dynamically inspects all public properties of an object and applies the associatedValidationAttributeto validate their values.
  3. Comprehensive Error Handling: The tool provides methods to retrieve errors in multiple formats:
  • GetErrors: Returns a collection of validation errors for detailed inspection.
  • GetErrorsString: Provides a string-formatted summary of all validation errors.

4.Ease of Use: Add a simpleIsValidmethod to your model, and the validator will handle everything from validation checks to error aggregation.

Sample Usage

using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;using System.Linq;using System.Text;using System.Threading.Tasks;using Microsoft.VisualBasic;namespace Employee_Management_System{    internal class EmployeeModel    {        public EmployeeModel() { }        [Required]        [Range(0, uint.MaxValue)]        public int EmployeeID { get; set; }        [Required]        [StringLength(100, MinimumLength = 2)]        public string Name { get; set; }        [Required]        public string Designation { get; set; }        [Required]        public string Department { get; set; }        [Required]        [RegularExpression(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$", ErrorMessage = "Please enter valid EmailID. ")]        public string Email { get; set; }        [Required]        [RegularExpression(@"^\d{8,}$", ErrorMessage = "Please enter valid PhoneNumber. ")]        public string Phone { get; set; }        [Required]        public DateTime JoiningDate { get; set; }        public EmployeeModel(int employeeID, string name, string designation, string department, string email, string phone, DateTime joiningDate)        {            EmployeeID = employeeID;            Name = name;            Designation = designation;            Department = department;            Email = email;            Phone = phone;            JoiningDate = joiningDate;        }    }}
Enter fullscreen modeExit fullscreen mode

Here’s how you can integrate and use the Global Class Validator in your .NET projects:

var employee = new EmployeeModel { Name = "", Email = "develop" }; // Example model with errors  bool IsValid = ClassModelValidator<EmployeeModel>.IsValid(employee);if (!IsValid){     MessageBox.Show( ClassModelValidator<EmployeeModel>.GetErrorsString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);}
Enter fullscreen modeExit fullscreen mode

Code Implementation

Below is the full implementation of theGlobalClassValidator class for your reference:

using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;using System.Linq;using System.Reflection;using System.Runtime.CompilerServices;using System.Security.Policy;using System.Text;using System.Threading.Tasks;namespace Employee_Management_System.Helper{    public static class ClassModelValidator<T> where T : class    {        // Errors list for tracking validation issues        [ThreadStatic]        private static List<string> Errors;        static ClassModelValidator()        {            Errors = new List<string>();        }        public static bool IsValid(T model)        {            if (model == null)            {                AddError("Model cannot be null.");                return false;            }            Errors.Clear();            foreach (var property in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance))            {                var value = property.GetValue(model);                foreach (var attribute in property.GetCustomAttributes<ValidationAttribute>())                {                    if (!attribute.IsValid(value))                    {                        AddError(attribute.FormatErrorMessage(property.Name));                    }                }            }            return Errors.Count == 0;        }        public static IEnumerable<string> GetErrors()        {            return Errors;        }        public static string GetErrorsString()        {            return string.Join(Environment.NewLine, Errors);        }        private static void AddError(string error)        {            if (!string.IsNullOrEmpty(error))            {                Errors.Add(error);            }        }    }}
Enter fullscreen modeExit fullscreen mode

Benefits of Using Global Class Validator

  • Enhances data integrity with minimal overhead.
  • Reduces boilerplate code by utilizing reflection and attributes.
  • Easily extensible for specific validation requirements.

With the Global Class Validator, you can ensure that your Employee Management System is robust, efficient, and error-free.

Feel free to integrate this utility into your projects and let us know how it transforms your validation processes!

Thanks for Reading!

For more details, visit:
🔗Employee Management System on GitHub

Direct link to the code:
🔗ClassModelValidator.cs

Feel free to explore the repository and contribute! 🚀

Top comments(1)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
anna_hajare_9520a4c4d15ee profile image
Anna Hajare
  • Joined

This article provides an insightful approach to implementing a global class validator for enhanced object validation in EMS. The structured methodology ensures consistency and efficiency in data validation across the system. A deeper dive into real-world use cases or a comparison with existing validation techniques would further enrich the discussion. Overall, a well-explained and practical guide!

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

.NET Developer with 3 years of experience in designing, developing, and maintaining web and desktop applications using C#, ASP.NET, MVC, and SQL Server. Skilled in building scalable solutions, API.
  • Location
    UP, India.
  • Education
    MCA
  • Work
    SWD @Mindstick.
  • Joined

More fromRavi Vishwakarma

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp