Search code examples
c#asp.net-mvccode-first

Join multiple Model properties into 1 property and get one error message for each of them


I have 4 string properties, each property for each textbox in my Asp.Net MVC view. I also have a property that concats the values of each into one:

public string ModelCode {get{return ProjNr+SerialNr+UserNr+ClientNr}}

So I want, if one of the properties doesn't fit the model requirements to get just one error message. Like when the user doesn't input the ClientNr instead of getting an error saying "Client required" it should show an error saying that the ModelCode doesn't meet the requirements.

EDIT: ProjNr, SerialNr, UserNr and ClientNr are required and they are strings.


Solution

  • You can implement IValidatableObject by your model class

    public class YourModel : IValidatableObject
    {
        public string ProjNr { get; set; }
        public string SerialNr { get; set; }
        public string UserNr { get; set; }
        public string ClientNr { get; set; }
        public string ModelCode => $"{ProjNr}{SerialNr}{UserNr}{ClientNr}";
        // ...
    
        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if (/*check if ProjNr or other fields not valid*/)
              yield return new ValidationResult(
                      "ModelCode doesn't meet the requirements",
                      new [] {"ModelCode"}); // return only ModelCode member
        }
    }
    

    Another option (if you want to rely on DataAnnotation attributes for validation of ProjNr, SerailNr, UserNr and ClientNr instead of validating them manually - you can check validation errors of those properties in controller and add new validation error if any errors found:

    var hasModelCodeErrors = ModelState["ProjNr"].Errors.Any()
        || ModelState["SerialNr"].Errors.Any()
        || ModelState["SerialNr"].Errors.Any()
        || ModelState["ClientNr"].Errors.Any();
    
    if (hasModelCodeErrors)
        ModelState.AddModelError("ModelCode", "ModelCode doesn't meet the requirements");