ASP.NET Custom Validator Client side & Server Side validation not firing

前端 未结 7 1583
梦毁少年i
梦毁少年i 2020-12-12 20:16

This has not happened to me before, but for some reason both the client and server side validation events are not being triggered:



        
7条回答
  •  粉色の甜心
    2020-12-12 20:52

    Your CustomValidator will only fire when the TextBox isn't empty.

    If you need to ensure that it's not empty then you'll need a RequiredFieldValidator too.

    Note: If the input control is empty, no validation functions are called and validation succeeds. Use a RequiredFieldValidator control to require the user to enter data in the input control.

    EDIT:

    If your CustomValidator specifies the ControlToValidate attribute (and your original example does) then your validation functions will only be called when the control isn't empty.

    If you don't specify ControlToValidate then your validation functions will be called every time.

    This opens up a second possible solution to the problem. Rather than using a separate RequiredFieldValidator, you could omit the ControlToValidate attribute from the CustomValidator and setup your validation functions to do something like this:

    Client Side code (Javascript):

    function TextBoxDCountyClient(sender, args) {
        var v = document.getElementById('<%=TextBoxDTownCity.ClientID%>').value;
        if (v == '') {
            args.IsValid = false;  // field is empty
        }
        else {
            // do your other validation tests here...
        }
    }
    

    Server side code (C#):

    protected void TextBoxDTownCity_Validate(
        object source, ServerValidateEventArgs args)
    {
        string v = TextBoxDTownCity.Text;
        if (v == string.Empty)
        {
            args.IsValid = false;  // field is empty
        }
        else
        {
            // do your other validation tests here...
        }
    }
    

提交回复
热议问题