简体   繁体   中英

One out of two fields required in validation

I have 2 fields:

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 . 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.

If you are willing to do this on client side this may give you a start

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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