[已解决]如何为我的CustomValidator和TextBox触发OnServerValidate事件?

问题描述:

我正在Windows XP和IE 8或Mozilla Firefox上使用Microsoft Visual Studio2010.

我有一个试图与CustomValidator一起使用的TextBox.但是,我似乎无法触发OnServerValidate事件.

这是我的ASP:

I am using Microsoft Visual Studio 2010 on Windows XP with either IE 8 or Mozilla Firefox.

I have a TextBox that I am trying to use a CustomValidator with. However, I can''t seem to get the OnServerValidate event to fire.

Here''s my ASP:

<asp:TextBox runat="server" Width="280" maxlength="80" id="txtEmail" />
<asp:CustomValidator runat="server" ID="cvEmail" ControlToValidate="txtEmail"
     SetFocusOnError="true" ValidateEmptyText="true" OnServerValidate="cvEmail_OnServerValidate" />


清单1. 用于设置自定义验证程序的代码.

这是隐藏的代码:


Listing 1. Code to set up the Custom Validator.

Here is the code-behind:

protected void cvEmail_OnServerValidate(object sender, ServerValidateEventArgs e)
    {
        // validate the email address in the text box using our Email Validator
        if (_validator != null)
        {
            string errorMessageText = string.Empty;
            if (_validator.ValidateEmailAddress(e.Value,
                ref errorMessageText))
            {
                // display the error message text
                errorMessageLabel.Font.Bold = true;
                errorMessageLabel.Text = errorMessageText;
                e.IsValid = false;
            }
            else
                e.IsValid = true;
        }
    }


清单2. OnServerValidate事件的代码隐藏.

应该注意的是,_validator是指向项目中另一个类的字段,并且_validator字段是在Page_Load中分配的.
感谢您的见解!

布莱恩


更新:
由OP自己解决-作为解决方案之一发布.


Listing 2. Code-behind for the OnServerValidate event.

It should be noted that _validator is a field which points to another class in the project, and the _validator field is allocated in Page_Load.

Thanks for any insight!

Brian


UPDATE:
Resolved by OP himself - posted as one of the solutions.

我在页面上其他地方有一个RequiredFieldValidator用于另一个TextBox,并且CustomFieldValidator仅在其他验证器也满足的情况下才触发;否则,没有意义,因为该页面已经无效.
My solution is that of course this was not firing; I had a RequiredFieldValidator elsewhere on the page for another TextBox and the CustomFieldValidator only fires if the other validator is also satisfied; otherwise, there''s no point, since the page is already invalid.