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-in ValidationAttributeand 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 associated ValidationAttributeto 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 simple IsValidmethod 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 mode Exit 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 mode Exit fullscreen mode

Code Implementation

Below is the full implementation of the GlobalClassValidator 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 mode Exit 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! πŸš€

Billboard image

Use Playwright to test. Use Playwright to monitor.

Join Vercel, CrowdStrike, and thousands of other teams that run end-to-end monitors on Checkly's programmable monitoring platform.

Get started now!

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay