加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-15 23:20:31 所属栏目:asp.Net 来源:网络整理
导读:我有两个字段有些电话号码和手机号码.就像是.. [Required] public string Phone { get; set; } [Required] public string Mobile{ get; set; } 但用户可以在其中任何一个中输入数据.一个是强制性的如何处理它们,即当用户在另一个字段中输入数据时,如何禁用一
我有两个字段有些电话号码和手机号码.就像是..
[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;
    }
}

您将应用于您的视图模型的其中一个属性:

public class MyViewModel
{
    [RequiredIfOtherFieldIsNull("Mobile")]
    public string Phone { get; set; }

    public string Mobile { get; set; }
}

那么你可以有一个控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }

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

最后,您将注册一个适配器来连接此自定义规则的客户端验证的视图:

@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而不是数据注释来对我的模型执行验证.实现这样简单的验证场景是以简单的方式来实现的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读