简体   繁体   中英

Validation of a List of an Annotated Model

I'm not really sure if the title is clear. Let me explain it better:

I have two models:

1- GuestResponse.cs:

public class GuestResponse
    {
        [Required(ErrorMessage="Please enter your name")]
        public string Name { get; set; }

        [Required(ErrorMessage = "Please enter your email address")]
        [RegularExpression(".+\\@.+\\..+", ErrorMessage="Please enter a valid email address")]
        public string Email { get; set; }

        [Required(ErrorMessage = "Please enter your phone number")]
        public string Phone { get; set; }

        [Required(ErrorMessage = "Please especify wheter you will attend")]
        public bool? WillAttend { get; set; }
    }

2- CompanyGuestResponse.cs:

public class CompanyGuestResponse
    {
        [Required(ErrorMessage = "Please enter your company name")]
        public string Name { get; set; }

        [Required(ErrorMessage = "Please enter your company email address")]
        [RegularExpression(".+\\@.+\\..+", ErrorMessage = "Please enter a valid email address")]
        public string Email { get; set; }

        [Required(ErrorMessage = "Please enter your company phone number")]
        public string Phone { get; set; }

        public IList<GuestResponse> GuestResponses { get; set;} 
    }

I have also a strongly-typed view for the CompanyGuestResponse model, in which there's a form with a table that will let the user provide input for the property GuestResponses.

I would like that the form could only be submitted if the filled rows of the table were validated correctly (that is, do not attempt to validate rows that are not filled) and that there was at least one row correctly filled.

I tried to do this by creating a custom annotation as described in ViewModel validation for a List with no success (mvc simply ignored the list annotation and validated the annotations in GuestResponse class):

[EnsureOneElementAttribute(ErrorMessage = "At least a person is required")]
public IList<GuestResponse> GuestResponses { get; set;} 

The result:

http://postimage.org/image/b2jn7ta69/

what i understand that you want to validate on the model itself, not every field, so what you can do remove the [Required] attribute on the properties, and in the Action validate if any of the fields are filled if so then continue else, add an error and dont associate it with any field

so what i am telling you drop annotation on this case and do a manual check

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