The easiest way to validate your data using Record Validator

Vishal Pathak
Abhima C# Programming
4 min readMay 5, 2024

--

Introduction

Data validation is a crucial part of the application, ensuring that all the data that is passed to the database or any other place like function, external application are meeting the criteria. If data is not having valid value then application should stop the flow. But to write the code to validate all the fields value is very tedious task and requires a lot of time. There are other disadvantages of writing the data validation code, such as:

  1. We have to write same validations on different places for different kinds of data object. For example there are two data objects employee and company both are having some fields which are mandatory but now we have to write same validation of avoiding empty values on both the objects.
  2. Writing too many code makes your code more complex to understand and it increases file size which, in turn, makes your application slow to load and degrades performance of the application.
  3. There are high chances that some constraints are not validated by the code which can create a lot of issues.

To avoid all the above issues we have made a library called Record Validator.

Record Validator is a powerful tool which supports almost all the types validation that you can think of in C#, It supports all the data type.

The main advantage of this tool is that you don’t have to write a single line of validation logic 🎉. Let’s see the example below to understand how to use this tool.

Example :-

public class Employee
{
[Mandatory("Id cannot be 0",validateForDefaultValue:true)]
public int id { get; set; }
[Mandatory]
public string name { get; set; }
[Mandatory]
public int age { get; set; }
[Mandatory(validateForDefaultValue:true)]
public decimal Salary { get; set; }
[Mandatory(validateForDefaultValue:true)]
public char Gender { get; set; }
[Date(minDate: "1995-01-01",maxDate: "2004-01-01", errorMessage:"Min date and max date should be satified")]
public DateTime Dob { get; set; }
[Date(minDate: "2004-01-01")]
public string JoiningDate { get; set; }
[Email]
public string EmailId { get; set; },
[RegularExpression(pattern: "^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[6789]\d{9}$",errorMessage:"Please enter indian mobile number")]
public string Mobile{ get; set; },

}

Here in the above code we have added a model class where we have used Record Validator attributes to provide constraints for all the fields. Now let’s see below, how to validate the object of Employee type with just a single line of code.

public class EmployeeService
{

public void ValidateEmployee()
{

try
{
var employee = new Employee();
employee = GetEmployeeData();
employee.ValidateValueAndThrowException();// Validates all the provided constraints against fields and throws the exception
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

}

public Employee GetEmployee()
{
var emp = new Employee()
{
Name = "Vishal Pathak",
age = 28,
Salary = 20000,
Gender = 'M',
Dob = new DateTime(1995, 01, 02),
JoiningDate = "2019-01-01",
Id = 1,
EmailId = "Vpathak154gmail.com",
Mobile="+919987544694"
};
}

}

As you can see in the above code, we have written only one line and the tool has validated all the field values against constraint attributes provided in the class. If validation fails then it will directly throw an error with all the details.

Output:-

//Invalid email for param EmailId.

We have one more method which can be called in case you don’t want to break your flow for the transaction. Just call ValidateValueAndReturnListOfExceptions function on the object. This method you can use if you don’t want to break your transaction flow and also you want to log the errors returned from the method. This function returns IList<RecordValidatorException> object which has two properties Param and ErrorMessage. Param contains the property name for which the error has been triggered and ErrorMessage property contains the actual error message for the property.

public class EmployeeService
{

public void ValidateEmployee()
{

try
{
var employee = new Employee();
employee = GetEmployeeData();
var exceptions = employee.ValidateValueAndReturnListOfExceptions();// Validates all the provided constraints against fields and throws the exception
foreach(var exception in exceptions)
{
Console.WriteLine($"Error - {exception.ErrorMessage} against {exception.Param}");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

}

public Employee GetEmployee()
{
var emp = new Employee()
{
Name = "Vishal Pathak",
age = 28,
Salary = 20000,
Gender = 'M',
Dob = new DateTime(1995, 01, 02),
JoiningDate = "2019-01-01",
Id = 1,
EmailId = "Vpathak154gmail.com",
Mobile="+919987544694"
};
}

}

Thank you for reading please comment your suggestions, share the article, follow me and Abhima C# Programming publication.

Bhagavad Gita Verse of the Day

ते तं भुक्त्वा स्वर्गलोकं विशालं
क्षीणे पुण्ये मर्त्यलोकं विशन्ति |
एवं त्रयीधर्ममनुप्रपन्ना
गतागतं कामकामा लभन्ते || 21||

BG 9.21: When they have enjoyed the vast pleasures of heaven, the stock of their merits being exhausted, they return to the earthly plane. Thus, those who follow the Vedic rituals, desiring objects of enjoyment, repeatedly come and go in this world.

--

--

Vishal Pathak
Abhima C# Programming

love ❤ coding, solving some industry problems technologies: JavaScript, C#, Angular, PLSQL, Docker Want to learn: Python, Go language, AI, ML and Cloud