You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FormView控件中自定义验证无法触发问题求助

Troubleshooting Your CustomValidator Not Triggering in FormView

Let’s walk through the most likely issues and fixes to get your past-date validation working as expected:

1. First: Confirm the Validation Function is Being Called

If your debugger statements aren’t triggering when you click the "Save" button, the CustomValidator isn’t even invoking your client-side function. Here’s why that might happen:

  • Script placement: Make sure your JavaScript code is placed after the FormView control in your page, or wrap it in a DOM-ready handler (like vanilla JS’s DOMContentLoaded event). If the script loads before the FormView’s controls exist, getElementById will return null, throwing an error that stops validation cold.
  • Check EnableClientScript: The CustomValidator has this property set to true by default, but double-check you didn’t accidentally set it to false—that would skip all client-side validation entirely.

2. Fix Date Parsing Issues

Your parseDate function relies on matching 3-letter month abbreviations to your months object, which can break in two common scenarios:

  • Culture mismatches: If your server’s regional settings output month abbreviations in a non-English format (e.g., "Janv" for French instead of "Jan"), your function will return an Invalid Date, causing the validation logic to fail silently.
  • Format inconsistencies: Test your parseDate function directly in the browser console with a sample date from your TextBox (e.g., parseDate("10-Apr-2023")). If it returns Invalid Date, update your months object to match the actual abbreviations being rendered, or switch to a more robust parsing method (like using Date.UTC for explicit date construction).

3. Handle Empty Text (If Required)

By default, CustomValidator skips validation if the target TextBox is empty. If you want to enforce that the date can’t be blank and can’t be in the past, add ValidateEmptyText="true" to your CustomValidator:

<asp:CustomValidator ID="CustomValidatorPlannedEndDate" runat="server" 
    ErrorMessage="Planned End date can't be in the past" 
    ClientValidationFunction="ValidatePastDates" 
    CssClass="text-danger" 
    ControlToValidate="TxtProjectPlannedEndDate" 
    Display="Dynamic"
    ValidateEmptyText="true">
</asp:CustomValidator>

4. Check for Uncaught JavaScript Errors

Open your browser’s Developer Tools (F12) and go to the Console tab. Click "Save" and look for errors like "Cannot read properties of null" or "Invalid Date". Even one unhandled error will stop the validation script from running, making it seem like the validator isn’t triggering.

5. Clean Up Role Check Logic

Your current role condition leaves args.IsValid untouched if the user isn’t a Basic User or Project Manager. To avoid ambiguity (and ensure validation behaves predictably), explicitly set args.IsValid for all role cases:

function ValidatePastDates(source, args) {
    var selectedDate = parseDate(document.getElementById('MainContent_FrmVwProjectDetails_TxtProjectPlannedEndDate').value);
    var projectStatus = document.getElementById('MainContent_FrmVwProjectDetails_ddlStatus');
    var projectStatusValue = projectStatus.options[projectStatus.selectedIndex].value;
    var userRole = document.getElementById('MainContent_hdnUserRole').value;
    var now = new Date();
    var dt1 = Date.parse(now);
    var dt2 = Date.parse(selectedDate);

    if (userRole.indexOf("Basic User") >= 0 || userRole.indexOf("Project Manager") >= 0) {
        // Enforce past date check for basic users/PMs
        args.IsValid = (dt2 >= dt1);
    } else {
        // Allow admins/managers to set past dates
        args.IsValid = true;
    }
}

Quick Isolation Test

To rule out complex logic, temporarily simplify your validation function to the bare minimum:

function ValidatePastDates(source, args) {
    alert("Validation triggered!");
    args.IsValid = false; // Force error message to display
}

If you see the alert, the validator is working, and the issue lies in your date parsing or role logic. If not, the problem is in the CustomValidator configuration or script loading.


内容的提问来源于stack exchange,提问作者vish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:17:51