简体   繁体   English

使用数据注释在 c# 中进行数据验证

[英]Data Validation in c# using Data Annotations

I'm migrating the client's data to the new database (SQL SERVER) for which I need to validate all the properties.我正在将客户端的数据迁移到我需要验证所有属性的新数据库 (SQL SERVER)。 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.但即使在添加了所需的属性、Regex、String Length 等之后......它根本没有被验证,它仍然接受所有 null、空值。 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

The problem is that the ValidationContext works with properties and not fields.问题是 ValidationContext 使用属性而不是字段。

I found the answer by decompiling the ValidationContext class to find out it will only search through properties.我通过反编译 ValidationContext 类找到了答案,发现它只会搜索属性。

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.看起来您也不需要在 Invoice.PinCode 字段上转换为 int 或 Validation 函数会因为它正在寻找一个字符串而崩溃。

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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM