I have a CSV file, which I need to ready and validate each element in each row and create a collection of a class, having valid data.
i.e CSV File looks like:
EmpID,FirstName,LastName,Salary
1,James,Help,100000
2,Jane,Scott,1000
3,Mary,Fraze,10000
Class looks like:
public class Employees
{
public int EmpID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Salary { get; set; }
public string ErrorReason { get; set; }
}
Here are the validations required for each field:
EmpID:
FirstName (same validation for LastName):
Salary:
To achieve this, here is my approach:
So, my question is, is this the right approach, or is there any other better/cleaner way of validating class properties.
Thanks
I would consider using the C# DataAnnotations namespace. I use them often for MVC models and they are very helpful.
The reason I think this would be helpful is that you can attempt to create a new Employees object in a try/catch block and catch ValidationExceptions such as:
List<Employees> empList = new List<Employees>();
foreach (var row in csvRows){
try {
//Parse the row here and create the object. don't do any validation here
var employee = CreateEmployeeFromRow(row);
empList.Add(employee);
}
catch (ValidationException ve){
//do whatever
}
}
Your class would look like:
using System.ComponentModel.DataAnnotations;
public class Employees
{
[Required, RangeAttribute(0, 99)]
public int EmpID { get; set; }
[Required, Length(30), RegularExpression("/^[A-Za-z]+$/")]
public string FirstName { get; set; }
[Required, Length(30), RegularExpression("/^[A-Za-z]+$/")]
public string LastName { get; set; }
[Required]
public decimal Salary { get; set; }
}
As far as avoiding duplicate employee IDs, I would just check that before you insert into your database. That doesn't really make an Employees object invalid (or the line in the CSV invalid because it is the proper format).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With