I'm migrating the client's data to the new database (SQL SERVER) for which I need to validate all the properties. I tried by adding data annotations but it's not working as expected.
here is my sample code:
public class SellerDetailModel
{
[Required, RegularExpression("[0-9]{2}[0-9A-Z]{13}")]
public string GSTNumber;
[Required, StringLength(100, MinimumLength = 3)]
public string LegalName;
[StringLength(100, MinimumLength = 3)]
public string TradingName;
[Required, StringLength(100, MinimumLength = 3)]
public string Address1;
[StringLength(100, MinimumLength = 3)]
public string Address2;
[Required, StringLength(50, MinimumLength = 3)]
public string Location;
[Required, StringLength(6)]
public int PinCode;
[Required, StringLength(2, MinimumLength = 1)]
public string StateCode;
[StringLength(12, MinimumLength = 6)]
public string ContactNumber;
[Required, StringLength(100, MinimumLength = 6)]
public string EmailId;
}
Now, in the other class (Business Logic) I'm assigning values to this class.
//"invoice" is an object having seller related data
SellerDetailModel dataTransferObject = new SellerDetailModel
{
GSTNumber = invoice.SellerGSTNumber,
LegalName = invoice.SellerLegalName,
TradingName = invoice.SellerTradingName,
Address1 = invoice.SellerAddress1,
Address2 = invoice.SellerAddress2,
Location = invoice.SellerLocation,
PinCode = Convert.ToInt32(invoice.SellerPinCode),
StateCode = invoice.SellerStateCode,
ContactNumber = invoice.SellerContactNumber,
EmailId = invoice.SellerEmailId,
};
but even after adding the required attribute, Regex, String Length etc...It's not being validated at all, it's still accepting all the null, empty values. Can someone please help me how can I validate these properties?
I just want to create a log data if some error occurred during this migration.
EDIT
I have already tried below method but still not working...
public string Validate()
{
ValidationContext context = new ValidationContext(this);
List<ValidationResult> results = new List<ValidationResult>();
bool isValid = Validator.TryValidateObject(this, context, results, true);
if (!isValid)
{
StringBuilder sbrErrors = new StringBuilder();
foreach (var validationResult in results)
{
sbrErrors.AppendLine(validationResult.ErrorMessage);
}
return sbrErrors.ToString();
}
else
return string.Empty;
}
var validation = dataTransferObject.Validate() //always gives string.Empty