asp.net-mvc-3 - 如何在 ASP .NET MVC 3 中验证与另一个值相关的一个字段

标签 asp.net-mvc-3

我有两个字段,例如电话号码和手机号码。就像是..

    [Required]
    public string Phone { get; set; }

    [Required]
    public string Mobile{ get; set; }

但用户可以在其中任何一个中输入数据。一个是强制性的。如何处理它们,即当用户在另一个字段中输入数据时如何禁用一个字段的必填字段验证器,反之亦然。在哪种情况下,我必须在 javascript 中处理它,我需要为此添加哪些脚本。任何人都可以请帮助找到解决方案...

最佳答案

一种可能性是编写自定义验证属性:

public class RequiredIfOtherFieldIsNullAttribute : ValidationAttribute, IClientValidatable
{
    private readonly string _otherProperty;
    public RequiredIfOtherFieldIsNullAttribute(string otherProperty)
    {
        _otherProperty = otherProperty;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var property = validationContext.ObjectType.GetProperty(_otherProperty);
        if (property == null)
        {
            return new ValidationResult(string.Format(
                CultureInfo.CurrentCulture, 
                "Unknown property {0}", 
                new[] { _otherProperty }
            ));
        }
        var otherPropertyValue = property.GetValue(validationContext.ObjectInstance, null);

        if (otherPropertyValue == null || otherPropertyValue as string == string.Empty)
        {
            if (value == null || value as string == string.Empty)
            {
                return new ValidationResult(string.Format(
                    CultureInfo.CurrentCulture,
                    FormatErrorMessage(validationContext.DisplayName),
                    new[] { _otherProperty }
                ));
            }
        }

        return null;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
            ValidationType = "requiredif",
        };
        rule.ValidationParameters.Add("other", _otherProperty);
        yield return rule;
    }
}

您将应用于 View 模型的属性之一:
public class MyViewModel
{
    [RequiredIfOtherFieldIsNull("Mobile")]
    public string Phone { get; set; }

    public string Mobile { get; set; }
}

那么你可以有一个 Controller :
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}

最后是一个 View ,您将在其中注册一个适配器来连接客户端验证这个自定义规则:
@model MyViewModel

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script type="text/javascript">
    jQuery.validator.unobtrusive.adapters.add(
        'requiredif', ['other'], function (options) {

            var getModelPrefix = function (fieldName) {
                return fieldName.substr(0, fieldName.lastIndexOf('.') + 1);
            }

            var appendModelPrefix = function (value, prefix) {
                if (value.indexOf('*.') === 0) {
                    value = value.replace('*.', prefix);
                }
                return value;
            }

            var prefix = getModelPrefix(options.element.name),
                other = options.params.other,
                fullOtherName = appendModelPrefix(other, prefix),
                element = $(options.form).find(':input[name="' + fullOtherName + '"]')[0];

            options.rules['requiredif'] = element;
            if (options.message) {
                options.messages['requiredif'] = options.message;
            }
        }
    );

    jQuery.validator.addMethod('requiredif', function (value, element, params) {
        var otherValue = $(params).val();
        if (otherValue != null && otherValue != '') {
            return true;
        }
        return value != null && value != '';
    }, '');
</script>

@using (Html.BeginForm())
{
    <div>
        @Html.LabelFor(x => x.Phone)
        @Html.EditorFor(x => x.Phone)
        @Html.ValidationMessageFor(x => x.Phone)
    </div>

    <div>
        @Html.LabelFor(x => x.Mobile)
        @Html.EditorFor(x => x.Mobile)
        @Html.ValidationMessageFor(x => x.Mobile)
    </div>

    <button type="submit">OK</button>
}

对于像我们在日常生活中遇到的验证规则这样极其简单的东西来说,这真是太恶心了。我不知道 ASP.NET MVC 的设计者在决定选择声明式验证方法而不是命令式验证时一直在想什么。

无论如何,这就是我使用 FluentValidation.NET 的原因而不是数据注释来对我的模型执行验证。实现这种简单的验证场景是以一种应该是简单的方式实现的。

关于asp.net-mvc-3 - 如何在 ASP .NET MVC 3 中验证与另一个值相关的一个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8906228/

相关文章:

asp.net-mvc - 重复用户添加到数据库

asp.net-mvc-3 - ASP.NET MVC 3 Ajax.ActionLink

c# - 数据过滤是否发生在 Controller 、服务或存储库层?

c# - 在 ASP.NET MVC 中安全和 "squarified"照片上传

c# - 将 AjaxOnlyAttribute 和 ChildActionOnlyAttribute 合并到一个 Action 过滤器中

asp.net-mvc - MVC 3 与 Razor 最佳实践

c# - 在 ASP.NET MVC 2 中显示自定义 403 错误页面

asp.net - LINQ:多对多关系,从列表中选择

ajax - 当我专门指定要替换的ID时,为什么我的Ajax.BeginForm重新加载整个页面?

html - 在 ASP.NET MVC 网站上嵌入视频