Reputation: 5249
I have 2 fields and I need to make one of the fields a required fields only if the other field has content of "NO" value in it. So I have researched online and this is what I ended up having. The only question I have and need help with this is the first part of the code where it calls this: .getElementByID
. How can I construct that? Or if you could shed some lights on will be great.
<script>
function Validate(source, args) {
if (document.getElementById('<%= TextBox1.ClientID %>').value.toUpperCase() == "NO" &&
document.getElementById('<%= TextBox2.ClientID %>').value.length == 0)
args.IsValid = false;
else
args.IsValid = true;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="TextBox2 Should Be Filled"
Display="Dynamic" ClientValidationFunction="Validate" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
<asp:Button ID="Button1" runat="server" Text="Button" />
</form>
</body>
</html>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Page.Validate();
if (!Page.IsValid)
Response.Write("TextBox2 should be filled");
}
}
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = !(this.TextBox1.Text.Equals("NO", StringComparison.CurrentCultureIgnoreCase) && this.TextBox2.Text.Length == 0);
Upvotes: 0
Views: 326
Reputation: 460208
The first error within sight is:
if (!Page.IsPostBack) // <--- here
{
Page.Validate();
if (!Page.IsValid)
Response.Write("TextBox2 should be filled");
}
Change !Page.IsPostBack
to Page.IsPostBack
since it makes no sense to validate user input if the page was not posted back yet.
According to your question about your clientside validation code: what is the problem actually? Does your code work, do you get an exception, does it postback even if it's invalid? What's going wrong?
Upvotes: 4