简体   繁体   English

验证中需要两个字段中的一个

[英]One out of two fields required in validation

I have 2 fields: 我有2个字段:

FirstName 名字

LastName

And only one of these is required. 并且只需要其中一个。 But if both are omitted, I want both fields to be highlighted. 但如果两者都省略,我希望两个字段都突出显示。 If one of them is filled in then the model is okay and the form should submit. 如果其中一个被填写,那么模型是可以的,表格应该提交。

How can this be done? 如何才能做到这一点?

You can use this library , it will help you to do something like this 你可以使用这个库 ,它可以帮助你做这样的事情

[RequiredIf("PropertyValidationDependsOn", true)]
   public string PropertyToValidate { get; set; }

All complex validation starts with your view model inheriting from IValidatableObject . 所有复杂的验证都从您继承自IValidatableObject的视图模型开始。 You then override Validate and put in your own validation rules. 然后,您覆盖验证并输入您自己的验证规则。

IEnumerable<ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
    if (String.IsNullOrWhiteSpace(FirstName) && String.IsNullOrWhiteSpace(LastName))
    {
        yield return new ValidationResult("A name must be entered.", new string[] { "FirstName", "LastName" });
    }
}

Note that this only ensures server side validation for this rule. 请注意,这仅确保此规则的服务器端验证。 If you want it client side, you'll need to write your own JavaScript / jQuery code to deal with the validation. 如果你想要客户端,你需要编写自己的JavaScript / jQuery代码来处理验证。

If you are willing to do this on client side this may give you a start 如果您愿意在客户端这样做,这可能会给您一个开始

HTML HTML

<input type="text" class="name" id="firstName" />
<input type="text" class="name" id="lastName" />
<input type="button" id="btnSubmit" value="submit" />

Button Click Event 按钮单击事件

$("#btnSubmit").click(function () {
    var isValid = false;
    $("input[class='name']").each(function (key, keyValue) {
        //alert(keyValue.value);
        if (keyValue.value.length > 0) {
            isValid = true;
            $(this).css("background", "White");
        }
        else {
            $(this).css("background", "RED");
        }
    })
    if (!isValid) {
        // do something 
    }
});

To prevent the form submit if not passed validation 如果未通过验证,则阻止表单提交

$('input[type=submit]').bind('click', function(e) {
   var isValid = false;
        $("input[class='name']").each(function (key, keyValue) {
            //alert(keyValue.value);
            if (keyValue.value.length > 0) {
                isValid = true;
                $(this).css("background", "White");
            }
            else {
                $(this).css("background", "RED");
            }
        })
        if (!isValid) {
           e.preventDefault() // prevents the form from being submitted
        }    
});

test it at http://jsfiddle.net/habo/UpmCv/ http://jsfiddle.net/habo/UpmCv/进行测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM