您是否可以为标准ASP.NET Web窗体验证器进行自定义客户端JavaScript验证?

Bri*_*ght 17 asp.net validation jquery webforms

您是否可以为标准ASP.NET Web窗体验证器进行自定义客户端JavaScript验证?

例如,使用asp:RequiredFieldValidator单独保留服务器端代码,但使用jQuery实现自己的客户端通知以突出显示字段或背景颜色.

Geo*_*off 22

是的我已经这样做了.我使用Firebug找出了Dot.Net JS函数,然后劫持了验证器函数

以下内容适用于所有验证器,纯粹是客户端.我用它来改变ASP.Net验证的显示方式,而不是实际验证的实现方式.它必须包装在$(document).ready()中,以确保它覆盖原始的ASP.net验证.

/**
 * Re-assigns a couple of the ASP.NET validation JS functions to
 * provide a more flexible approach
 */
function UpgradeASPNETValidation(){
    // Hi-jack the ASP.NET error display only if required
    if (typeof(Page_ClientValidate) != "undefined") {
        ValidatorUpdateDisplay = NicerValidatorUpdateDisplay;
        AspPage_ClientValidate = Page_ClientValidate;
        Page_ClientValidate = NicerPage_ClientValidate;
   }
}

/**
 * Extends the classic ASP.NET validation to add a class to the parent span when invalid
 */
function NicerValidatorUpdateDisplay(val){
    if (val.isvalid){
        // do custom removing
        $(val).fadeOut('slow');
    } else {
        // do custom show
        $(val).fadeIn('slow');
    }
}

/**
 * Extends classic ASP.NET validation to include parent element styling
 */
function NicerPage_ClientValidate(validationGroup){
    var valid = AspPage_ClientValidate(validationGroup);

    if (!valid){
        // do custom styling etc
        // I added a background colour to the parent object
        $(this).parent().addClass('invalidField');
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这是我在工作中使用的代码,我在没有那篇文章的情况下想出了自己.OP说他想使用jQuery.去点燃其他人. (21认同)

Mar*_*ade 11

标准的CustomValidator具有ClientValidationFunction属性:

<asp:CustomValidator ControlToValidate="Text1" 
                     ClientValidationFunction="onValidate" />

<script type='text/javascript'>
function onValidate(validatorSpan, eventArgs)
 { eventArgs.IsValid = (eventArgs.Value.length > 0);
   if (!eventArgs.IsValid) highlight(validatorSpan);
 }
</script>
Run Code Online (Sandbox Code Playgroud)