2010-02-12 100 views
1

我已經有了一些帶有文本框的簡單表單。這些文本框都有一個RequiredFieldValidator。如果填充字段1,則需要禁用字段2的RequiredFieldValidator,因爲只需要其中一個字段。什麼是完成這個最好的方法?使用asp.net驗證器驗證2個字段中的1個

回答

1

目前我用JavaScript解決了它的處理程序,我可以正常使用的驗證。

<script language="javascript" type="text/javascript"> 
function CheckPhoneValidator(txtEmail) 
{ 
    var phoneValidator = document.getElementById('<%= ReqPhone.ClientID %>'); 
    ValidatorEnable(phoneValidator, txtEmail.value == '' ? true : false); 
} 

function CheckEmailValidator(txtPhone) 
{ 
    var emailValidator = document.getElementById('<%= ReqEmail.ClientID %>'); 
    var emailRegexValidator = document.getElementById('<%= RegexEmail.ClientID %>'); 
    ValidatorEnable(emailValidator, txtPhone.value == '' ? true : false); 
    ValidatorEnable(emailRegexValidator, txtPhone.value == '' ? true : false); 
} 

而這些控件:

<tr> 
    <td> 
     E-mail adres: 
    </td> 
    <td> 
     <asp:TextBox ID="TxtEmail" runat="server" onchange="javascript:CheckPhoneValidator(this);"></asp:TextBox> 
     <asp:RequiredFieldValidator ID="ReqEmail" runat="server" ControlToValidate="TxtEmail" ErrorMessage="U moet een e-mail invullen als u geen telefoonnummer heeft ingevuld." Display="Dynamic" ValidationGroup="Contact">&nbsp;</asp:RequiredFieldValidator> 
     <asp:RegularExpressionValidator ID="RegexEmail" runat="server" ControlToValidate="TxtEmail" ErrorMessage="Dit is geen geldig e-mail adres." Display="Dynamic" ValidationExpression="([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})" ValidationGroup="Contact">&nbsp;</asp:RegularExpressionValidator> 
    </td> 
</tr> 
<tr> 
    <td> 
     Telefoonnummer: 
    </td> 
    <td> 
     <asp:TextBox ID="TxtPhone" runat="server" onchange="javascript:CheckEmailValidator(this);"></asp:TextBox> 
     <asp:RequiredFieldValidator ID="ReqPhone" runat="server" ControlToValidate="TxtPhone" ErrorMessage="U moet een telefoonnummer invullen als u geen e-mail heeft ingevuld." Display="Dynamic" ValidationGroup="Contact">&nbsp;</asp:RequiredFieldValidator> 
    </td> 
</tr> 
1

在這種情況下,使用CustomValidator與服務器端驗證處理程序更簡單。你應該自定義驗證添加到兩個控件:

<asp:TextBox runat="server" id="control1" /> 
<asp:CustomValidator runat="server" id="cusCustom1" controltovalidate="control1" onservervalidate="cusCustom_ServerValidate" errormessage="your message" /> 
<asp:TextBox runat="server" id="control2" /> 
<asp:CustomValidator runat="server" id="cusCustom2" controltovalidate="control2" onservervalidate="cusCustom_ServerValidate" errormessage="your message" /> 

和實施類似

protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e) 
{ 
    e.IsValid = (!string.IsNullOrempty(control1.Text)) || (!string.IsNullOrempty(control2.Text)) 
} 
+0

爲什麼只是服務器端驗證處理?爲什麼不是客戶端和服務器端? – rrrr 2010-02-12 09:12:01

+0

當然。 CustomValidator標籤可以具有額外的ClientValidationFunction =「customJSValidatingFunction」屬性。 – PanJanek 2010-02-12 09:20:11