Asp.net
您可以為標準 ASP.NET Web 表單驗證器進行自定義客戶端 javascript 驗證嗎?
您可以為標準 ASP.NET Web 表單驗證器進行自定義客戶端 javascript 驗證嗎?
例如,使用 asp:RequiredFieldValidator 保留伺服器端程式碼,但使用 jQuery 實現您自己的客戶端通知以突出顯示欄位或背景顏色。
標準的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>
是的,我已經這樣做了。我使用 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'); } }