1

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
Okasha Momin
  • 191
  • 3
  • 15
  • 1
    Attributes do not validate anything. They tell a validator how to validate. Do you have a validator in the first place? And, the task of validating model properties is pretty much unrelated to the database you are using. – GSerg Sep 30 '20 at 21:45
  • @GSerg can you please explain me how can I add validator? (I'm new in c#) – Okasha Momin Sep 30 '20 at 21:47
  • Does this answer your question? [How to manually validate a model with attributes?](https://stackoverflow.com/questions/17138749/how-to-manually-validate-a-model-with-attributes) – GSerg Sep 30 '20 at 21:49
  • I Tried this but it's still not working, – Okasha Momin Sep 30 '20 at 22:04

1 Answers1

2

The problem is that the ValidationContext works with properties and not fields.

I found the answer by decompiling the ValidationContext class to find out it will only search through properties.

You'll need to change your code to this to get it to work, where the fields have been converted to properties.

public class SellerDetailModel
{
    [Required, RegularExpression("[0-9]{2}[0-9A-Z]{13}")]
    public string GSTNumber { get; set; }

    [Required, StringLength(100, MinimumLength = 3)]
    public string LegalName { get; set; }

    [StringLength(100, MinimumLength = 3)] 
    public string TradingName { get; set; }

    [Required, StringLength(100, MinimumLength = 3)]
    public string Address1 { get; set; }

    [StringLength(100, MinimumLength = 3)]
    public string Address2 { get; set; }

    [Required, StringLength(50, MinimumLength = 3)]
    public string Location { get; set; }

    [Required, StringLength(6)]
    public string PinCode { get; set; }

    [Required, StringLength(2, MinimumLength = 1)]
    public string StateCode { get; set; }

    [StringLength(12, MinimumLength = 6)]
    public string ContactNumber { get; set; }

    [Required, StringLength(100, MinimumLength = 6)]
    public string EmailId { get; set; }

    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 (ValidationResult validationResult in results)
            {
                sbrErrors.AppendLine(validationResult.ErrorMessage);
            }
            return sbrErrors.ToString();
        }
        else
            return string.Empty;
    }
}

It also looks like you don't need the conversion to int on the Invoice.PinCode field or the Validation function will blow up since it is looking for a string.

public class Invoice
{
    public string SellerGSTNumber { get; set; }
    public string SellerLegalName { get; set; }
    public string SellerTradingName { get; set; }
    public string SellerAddress1 { get; set; }
    public string SellerAddress2 { get; set; }
    public string SellerLocation { get; set; }
    public string SellerPinCode { get; set; }
    public string SellerStateCode { get; set; }
    public string SellerContactNumber { get; set; }
    public string SellerEmailId { get; set; }
}

public class Mapper
{
    public static SellerDetailModel Map(Invoice invoice)
    {
        SellerDetailModel dataTransferObject = new SellerDetailModel
        {
            GSTNumber = invoice.SellerGSTNumber,
            LegalName = invoice.SellerLegalName,
            TradingName = invoice.SellerTradingName,
            Address1 = invoice.SellerAddress1,
            Address2 = invoice.SellerAddress2,
            Location = invoice.SellerLocation,
            PinCode = invoice.SellerPinCode,
            StateCode = invoice.SellerStateCode,
            ContactNumber = invoice.SellerContactNumber,
            EmailId = invoice.SellerEmailId,
        };

        return dataTransferObject;
    }
}
Mykezero
  • 36
  • 4