jwaliszko / ExpressiveAnnotations

Annotation-based conditional validation library.
MIT License
351 stars 123 forks source link

Can't get the RequiredIf to work #180

Open stesvis opened 6 years ago

stesvis commented 6 years ago

I want to use the same form and view model for user registration and user edit. In the first case, the password should be required. In the second case, it should be optional.

What I did, is use the RequiredIf annotation like this: [RequiredIf("string.IsNullOrWhiteSpace(Id)", AllowEmptyStrings = false, ErrorMessage = "The Password field is required.")]

so that the passwordd is required if the user Id is null or empty.

This is my view model:

public class UserViewModel
{
        public string Id { get; set; }

        // other fields...

        [RequiredIf("string.IsNullOrWhiteSpace(Id)", AllowEmptyStrings = false, ErrorMessage = "The Password field is required.")]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }
}

In my view I also included @Scripts.Render("~/bundles/expressive").

The problem is that when I submit the form, the password field never shows the error message and jqueryval treats it as valid.

joshnoe commented 6 years ago

Is Id included in the view (possibly as a hidden field)? If not, then it won't be included in the view model in the POST.

Maybe post your view code here too?