DEV Community

Ravi Vishwakarma
Ravi Vishwakarma

Posted on

1

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

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (1)

Collapse
 
anna_hajare_9520a4c4d15ee profile image
Anna Hajare β€’

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!

Image of Docusign

πŸ› οΈ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay