Fousana
Fousana

Reputation: 41

How to show required field validation conditionally from a view

In My MVC 4 application, I have a Multi Select List Box, where I can select multiple values, I also has an Item New Role as one of the list items, which also refers to a model property NewRole.

So using Jquery whenever the user selections contain New Role, I will provide a text box to the user, which is bind to NewRole from model as given,

@Html.TextBoxFor(m => m.NewRole) 

Which also has the following evaluation field.

@Html.ValidationMessageFor(m => m.NewRole)

And I will hide this text-box if the user selected options does not has the Item New Role.

Now the problem is even if I hide the div which contain the Text Box, it will try evaluating the required field validation.

What I require is When User Selects New Role and the User did not enter anything in the provided text Box then validate the required field property.

I know I can write a JQuery to show an alert when the div visible and does't has any value. But I want this default validation should happen on that condition.

is it possible?

Upvotes: 0

Views: 1382

Answers (3)

Kazi Manzur Rashid
Kazi Manzur Rashid

Reputation: 1544

Try using the rules add and remove, when new role is selected add new rule which validates the textbox on other selection remove the rule from text box and hide it like you are doing:

http://validation.bassistance.de/rules/

Upvotes: 1

M80
M80

Reputation: 994

One of the trick to avid certain client side validation conditionally ... you can use the IGNORE attribute of the validation ...

jQuery Validate Ignore elements with style

$("#myform").validate({
   ignore: ":hidden"
});

If this is not what you are looking ... I will provide more specific information

Upvotes: 1

Marko
Marko

Reputation: 13243

Yes it is possible with RemoteAttribute. Take a look at this article:

http://msdn.microsoft.com/en-us/library/gg508808(v=vs.98).aspx

Keep in mind that this is NOT client side validation meaning there is an actual server post happening.

Upvotes: 1

Related Questions