How to validate against Multiple validation groups?

后端 未结 4 1316
梦如初夏
梦如初夏 2021-01-04 20:03

I have two validation groups: parent and child

I have an add button that needs to only validate the child validation group which is easily done. The save button ne

4条回答
  •  走了就别回头了
    2021-01-04 20:35

    The problem with CAbbott's answer is that validation errors that occur in the "parent" group will not be displayed after the call to validate the "child" group. The more minor problem with Oleg's answer is that validation of the "child" group will not occur until the "parent" group is ready.

    All we really need to do to allow client-side validation of more than one group at the same time is to override the Javascript IsValidationGroupMatch method which determines whether or not a control is to be included in the current set being validated.

    For example:

    (function replaceValidationGroupMatch() {
    
        // If this is true, IsValidationGroupMatch doesn't exist - oddness is afoot!
        if (!IsValidationGroupMatch) throw "WHAT? IsValidationGroupmatch not found!";
    
        // Replace ASP.net's IsValidationGroupMatch method with our own...
        IsValidationGroupMatch = function(control, validationGroup) {
            if (!validationGroup) return true;
    
            var controlGroup = '';
            if (typeof(control.validationGroup) === 'string') controlGroup = control.validationGroup;
    
            // Deal with potential multiple space-delimited groups being validated
            var validatingGroups = validationGroup.split(' ');
    
            for (var i = 0; i < validatingGroups.length; i++) {
                if (validatingGroups[i] === controlGroup) return true;
            }
    
            // Control's group not in any being validated, return false
            return false;
        };
    } ());
    
    // You can now validate against multiple groups at once, for example:
    // space-delimited list.  This would validate against the Decline group:
    //
    //  Page_ClientValidate('Decline');
    //
    // while this would validate against the Decline, Open and Complete groups:
    //
    //  Page_ClientValidate('Open Decline Complete');
    //
    // so if you wanted to validate all three upon click of a button, you'd do:
    
    
    

提交回复
热议问题