Page.IsValid return false when disabled ASP.Net Validation using JavaScript

Last Reply 8 days ago By Corobori

Posted 12 days ago

I have got some doubts Enable Disable ASP.Net Validator (Client Side Validation) using JavaScript or jQuery 

it does indeed disable the validation but when the validation is disabled on the server side it doesn't seem to understand it that way.

In other words if I add an event on the button and test if the page is valid it says "no" even when I disable the validation and don't input anything in that field, I am expecting that if the field is not required I should be able to go on with what I want to do. My real live situation requires it: meaning depending on if a checkbox is enabled or not a validation must be done or not (which the sample does perfectly) but on the server side I am expecting a Me.IsValid=true if the validation is disabled on the client side. I guess I am missing something, any idea what ?

See https://www.screencast.com/t/rTThd60h

Posted 11 days ago Modified on 11 days ago

Hi Corobori,

Page.IsValid is calculated serverside and doesn't know that you switched the javascript validation off clientside.

Serverside you can check wheter Checkbox1 is checked to ignore validation i.e. add runat="server" to the checkbox.

HTML

UserName:
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="valName" ControlToValidate="txtName" runat="server"
    ErrorMessage="*Required" ForeColor="Red" ValidationGroup="Group1" />
<br />
Enable Validation:
<input type="checkbox" id="CheckBox1" onclick="ToggleValidator(this);" checked="checked"
    runat="server" />
<br />
<asp:Button ID="Button1" Text="Submit" runat="server" ValidationGroup="Group1" OnClick="Submit" />
<script type="text/javascript">
    function ToggleValidator(chk) {
        var valName = document.getElementById("<%=valName.ClientID%>");
        ValidatorEnable(valName, chk.checked);
    }
</script>

C#

protected void Submit(object sender, EventArgs e)
{
    if (IsValid || !CheckBox1.Checked)
    {

    }
    else
    {

    }
}

VB.Net

Protected Sub Submit(ByVal sender As Object, ByVal e As EventArgs)
    If IsValid OrElse Not CheckBox1.Checked Then
    Else
    End If
End Sub

 

 


Posted 8 days ago

Thank you pandeyism but this didn't answer the issue. I found by myself the solution. The issue is that the server side doesn't know that the validation has been disabled on client side so you need to add to override the validation using the following code.

Public Overrides Sub Validate(ByVal grp As String)
    Dim enableValidators As Boolean = CheckBox1.Checked
    valName.Enabled = enableValidators
    MyBase.Validate()
End Sub

And then in the submit button add the following the code. 

Page.Validate("Group1")
If Me.IsValid Then