Using validators to ensure that user filled either one of two required fields

穿精又带淫゛_ 提交于 2019-12-12 11:04:20

问题


I have an ASP.NET form for currency exchange requests. There are two text fields there: amount-source and amount-target.

One of them must be filled and only one.

How to implement this using Validators, if applicable?


回答1:


You can use Custom Validators for this:

<asp:Textbox id="textbox1" runat="server" />
<asp:CustomValidator id="valCustom" runat="server"
    ControlToValidate="textbox1"
    ClientValidationFunction="ClientValidate"
    OnServerValidate="ServerValidate"
    ErrorMessage="*You can only enter 1" display="dynamic">*
</asp:CustomValidator>

<asp:Textbox id="textbox2" runat="server" />
<asp:CustomValidator id="valCustom2" runat="server"
    ControlToValidate="textbox2"
    ClientValidationFunction="ClientValidate"
    OnServerValidate="ServerValidate"
    ErrorMessage="*You can only enter 1" display="dynamic">*
</asp:CustomValidator>

<script language="Javascript">
  function ClientValidate(source, arguments)
  {
    var tb1 = document.getElementById("<%=textbox1.ClientID %>").value;
    var tb2 = document.getElementById("<%=textbox2.ClientID %>").value;
    if (tb1 && tb2 || (!tb1 && !tb2)){
        arguments.IsValid = false;
    } else {
        arguments.IsValid = true;
    }
  }
</script>

Server-side:

protected void ServerValidate(object sender, ServerValidateEventArgs args)
{
  if(string.isNullOrEmpty(textbox1.Text) && string.isNullOrEmpty(textbox2.Text))
    args.IsValid = false;
  else if(!string.isNullOrEmpty(textbox1.Text) && !string.isNullOrEmpty(textbox2.Text))
    args.IsValid = false;
  else
    args.IsValid = true;
}

If you're using jQuery please comment...this can all be much cleaner.




回答2:


I would implement a custom Validator and decorate both TextBoxes with it. If both are filled, then both are in a error state.



来源:https://stackoverflow.com/questions/2171920/using-validators-to-ensure-that-user-filled-either-one-of-two-required-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!