ExpressiveAnnotations icon indicating copy to clipboard operation
ExpressiveAnnotations copied to clipboard

Can't get the RequiredIf to work

Open stesvis opened this issue 8 years ago • 1 comments

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.

stesvis avatar Dec 01 '17 20:12 stesvis

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?

joshnoe avatar Jan 10 '18 18:01 joshnoe