Require validation only if the field is visible

北城以北 提交于 2019-12-03 01:24:44
Prasad

With some useful hints from @Josiah, i am able to get to my requirement.

Add the RequiredIfAttribute class and the required javascript. Refer Conditional Validation in ASP.NET MVC 3

And in the class add the RequiredIf attribute as:

public class User
{
[RequiredIf("hFirstName", "true", ErrorMessage = "First Name is required")]
public string FirstName { get; set; }

and in aspx:

@Html.TextBoxFor(model => Model.FirstName, new { @style = "height:auto;" })
@Html.ValidationMessageFor(model => Model.FirstName)
@Html.Hidden("hFirstName")

Set the value of hFirstName to 'true' if the FirstName field is hidden and 'false', if visible.

The magic works with these changes. Thanks to @Josiah Ruddell for his answer

I would create a conditionally required attribute. There is a good article on creating one with jQuery validation here.

Another option: you could reference a project like Foolproof validation (codeplex) that provides this functionality and the client scripts.

Additionally you could utilize ajax to load your partial views so that they are never on the page when hidden. This would avoid conditional validation altogether.

Try my custom validation attribute:

[ConditionalRequired("hFirstName==true")]
public string FirstName {get, set};

It supports multiple conditions.

A bit late,

namespace System.ComponentModel.DataAnnotations
{
    public class RequiredIfVisibleAttribute : RequiredAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext context)
        {
            if (HttpContext.Current.Request.Form.AllKeys.Contains(context.MemberName))
                return base.IsValid(value, context);

            return ValidationResult.Success;
        }
    }
}

But here's my solution.

Just an inheritance of Required that will act the same way, except that it will only activate if the field if included in the posted keys.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!