2

I am using javascript unobtrusive validation. I have a view model that I am re-using for several forms, and in some of the forms, some properties on the view model are required. On other forms they shouldn't be. Is there a way to programmatically set [Required] on properties, so that I can accomplish this?

Thanks!

4 Answers 4

8

Cannot be done using DataAnnotations as these are implemented at compile time and cannot be added dynamically. You can either

Create different View Models that have the proper annotations

or

Have a service that you send the view model to that checks the model based on the action that it is coming from and return a list of validation errors that you can append to your model state

or

Put a property on the ViewModel such as string IsBeingUsedFor and use that in combination with a RequiredIf DataAnnotation. Here is an example of a library already build that uses conditional DataAnnotations. Then you can say, [RequireIf("IsBeingUsedFor", "Action_A")]

These aren't necessarily all of the options, but the some of the cleaner ones. You could do this all in JavaScript, but you will lose server side validation and could open up some holes in your application if a 'bad person' submits the form and bypasses client side validation.

Sign up to request clarification or add additional context in comments.

1 Comment

Great info! From taking another look at what I need, I think I can make a viewmodel that inherits from my base view model and get away with it. If not, I'll try RequiredIf.
4

I don't know of any way to do this with data annotations. However, in your view you can add/remove the required rule in javascript.

$("#myProperty").rules("add", { required: true });

or

$("#myProperty").rules("remove", "required");

1 Comment

That's good to know, thanks! I'll probably use RequiredIf, but will keep this in mind.
2

Attributes are accessed at runtime via reflection so im not aware you can turn off and on when you want. My advice would be to create a "Required" ViewModel and a "NotRequired" view model. I know you this is probably what you want, but it would be the easiest method i can think of.

Comments

0

If client-side validation is enough for you, then you can do the following in your Razor view, for example:

    @Html.LabelFor(model => model.title, new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @if (Model.IsTitleRequired == true)
        {
            @Html.TextBoxFor(model => model.title, new { @required = true })
        }
        else
        {
            @Html.TextBoxFor(model => model.title)
        }
        @Html.ValidationMessageFor(model => model.title)
    </div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.