Thursday, November 26, 2009

Read Page.IsValid from javascript (alternate way)

This was my scenario:
In a form there are few fields and 2 buttons :"Save" and "Cancel"
If user presses save button, and if the form validation is true, then immediately disable the "Cancel" button, so that the user cannot press the "Cancel" button. Here is the form:

"Name" field is a required field. So there is a "RequiredFieldValidator" attached with it. I have to disable the cancel button from javascript if:
1. User presses "Save" button.
2. Name field has some value (page validation passed).

To do this, I had to add a customvalidator with the name field, and do the javascript coding inside its client side function. Here is the code for the field and the validators:

<asp:TextBox ID="uxName" runat="server" MaxLength="50" width="180px"></asp:TextBox>

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="uxName" SetFocusOnError="true"
ErrorMessage="Department name cannot be empty" ValidationGroup="DepartmentEditValidation">*</asp:RequiredFieldValidator>

<asp:CustomValidator runat="server" ID="uxCustomValidator" ClientValidationFunction="checkNames" ControlToValidate="uxName" ValidationGroup="DepartmentEditValidation" ErrorMessage="" SetFocusOnError="True" Display="Dynamic">


Here is the code for Save, and Cancel button. Validation Group has to be same for the Save button.

<div class="editPanelButton">
<asp:Button ID="uxSave" runat="server" Text="<%$Resources:Texts,Save %>" ValidationGroup="DepartmentEditValidation"
OnClick="uxSave_Click" />
<asp:Button ID="uxCancel" runat="server" Text="<%$Resources:Texts,Cancel %>" OnClick="uxCancel_Click" />

Now we need to do the javascript checking inside the clientside function of the customfield validator. We declared: ClientValidationFunction="checkNames", so here is the function:

<script type="text/javascript" >
function checkNames(source, args){




args.IsValid is the alternate way of checking whether the page validation is true or not. Then I checked the validation was fired by pressing the "save" button. validation also fires when focus goes out from the "uxname" text field. So, I needed to be specific. If the conditions pass the I disabled the cancel button. This solved my problem.


SwethaReddy said...

i had tried page_isvalid in client side..eventhough validations fire..its returns true value..can u suggest me alternate way

SwethaReddy said...

the same page_is valid is not working, even though validations fire,it returns true value.y so can u suggest me

cosmicice said...

@SwethaReddy: It seems like the client side code is running before Page_isValid is updated. Try running Page_ClientValidate() first, and then check...