DataMember attributes for Data validation

前端 未结 3 889
野的像风
野的像风 2020-12-29 14:12

I am looking to place attributes on my WCF data contract members to validate string length and possibly use regex for more granular parameter validation.

I can the

3条回答
  •  不思量自难忘°
    2020-12-29 14:58

    Add System.ComponentModel.DataAnnotations reference to your project.

    The reference provides some DataAnnotations which are:

    RequiredAttribute, RangeAttribute, StringLengthAttribute, RegularExpressionAttribute

    you can in your datacontract like below.

        [DataMember]
        [StringLength(100, MinimumLength= 10, ErrorMessage="String length should be between 10 and 100." )]
        [StringLength(50)]     // Another way... String max length 50
        public string FirstName { get; set; }
    
        [DataMember]
        [Range(2, 100)]
        public int Age { get; set; }
    
        [DataMember]
        [Required]
        [RegularExpression(@"\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b", ErrorMessage = "Invalid Mail id")]
        public string Email { get; set; }
    

    Hope this helps.

提交回复
热议问题