简体   繁体   中英

Validate fields which are only provided in API JSON body using .NET Data Annotations

I am working on .NET Core Web API project, I have few data models and implemented data annotations.

While updating user profile, user can enter all fields or only some fields in API JSON body.

How do I check and apply data annotation only if specific field is provided in API JSON.

Note: User Id cannot be updated, it is only for reference.

In below model, I have 4 fields, only User Id is mandatory to be provided in API JSON rest all fields are optional to be entered in JSON while updating.

Conditions:

  • If any field is provided in API JSON, then it should not be NULL or empty value

  • If any field is not provided except user_id , it can ignore and do check null annotation for the fields provided.

I know we can validate by removing Required() for each column and validate manually.

Example:

JSON1

{
  "user_id":"XYZ-123"
}

Expected Result: Since no optional fields provided, it should Accept and pass validation

Example:

JSON2

{
  "user_id":"XYZ-123",
  "work_phone":"+91-987654320"
}

Expected Result: Since only work phone is provided, it should Accept and pass validation

Data Model:

public class UserDetails
    {

        [Required(AllowEmptyStrings = false, ErrorMessage = "The user_id field is required.")]
        [JsonProperty("user_id")]
        public string? UserId{ get; set; }

        [Required(AllowEmptyStrings = false, ErrorMessage = "The home_phone field is required.")]
        [JsonProperty("home_phone")]
        public string? HomePhone { get; set; }

        [Required(AllowEmptyStrings = false, ErrorMessage = "The work_phone field is required.")]
        [JsonProperty("work_phone")]
        public string? WorkPhone { get; set; }

        [Required(AllowEmptyStrings = false, ErrorMessage = "The mobile_phone field is required.")]
        [JsonProperty("mobile_phone")]
        public string? MobilePhone { get; set; }
}

I don't think it's possible if you don't get rid of the Required() attribute. Required is a data annotation for the view. The view will require it to have a value prior to accepting a form post.

If you want it to be a must in some case, you can refer to this post . The RequiredIf() attribute used by DrCopyPaste's answer might help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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