RobVious
RobVious

Reputation: 12915

Client-side validation for custom editor templates in MVC4

I have a viewModel that contains an object. I've defined a custom editor template for that object, which allows me to edit each of the children of that object. The children values aren't required serverside (so I don't have any Required annotations), however if the user reaches this particular input, it should be required.

Is there any way I can inspect the values of these children objects (within the viewModel) in the POST method, and return some errors to the view if they are null?

I'm using Razor.

Upvotes: 1

Views: 1361

Answers (2)

rae1
rae1

Reputation: 6144

On the server-side, you could check the child objects of the class in your action,

[HttpPost]
public ActionResult Edit(MyClass myClass)
{
    if (myClass.Children.Any(child => child == null))
    {
        foreach(var child in myClass.Children
            .Where(child => child == null)
            .Select((item, index) => new { Item = item, Index = index))
        {

             ModelState.AddModelError(
                 string.Format("Children[{0}]", child.Index), 
                 "Must be required");
        }

        return this.View("...");
    }
}

Upvotes: 1

Display Name
Display Name

Reputation: 4732

What you can do is to write a function that will be check user input (on change in that field)

if the user reaches this particular input

and if user reaches that particular input you use jQuery to add @class = "required" HTML attribute to your object. From that moment on it will become required

Take a look here: this is jQuery validator for required field based on some condition. I think this is exactly what you're after

Edit

Your other option is to use AJAX to go back to server to verify what you're looking for. Example is here

Hope this makes sense and is of help to you.

Upvotes: 0

Related Questions