ICodeFactory Labs

How to trigger an ASP.NET validator from JavaScript?

by Lacio 7. October 2009 04:40

Have you ever been in a situation when You were not able to perform server side validation and were not able to trigger the validators in the standardized way. By this I mean that you had a button that was doing a submit, but without causing any postback, and doing it all through JavaScript. In my case, I had a pagemethod that was doing a save for some entity we needed. So because of the nature of this operation, I needed to do a validation – and off course I used different kinds of validators – from range to required field and custom validators. So what is the problem then – the problem is that the JavaScript hides the form for the insert and the validation messages get lost, and along the way either a false insert or an exception is thrown – some fields might even be potential security breaches without proper validation. So I wandered around trying to find a way to perform regular validation, the way it is supposed to be done. I found a nice, elegant way to do it and even make it reusable on all the pages that need JavaScript validation and have the same problems as stated above.

 

An example of how validation works:

 

blogpic

 

So the solution is to write a small JavaScript function that will invoke all the validators that belong to a certain group. Below is the JavaScript function.

 

function ValidateEntry(validationGroup) {

  var isValidEntry = true;

  if (typeof (Page_Validators) != 'undefined') {

    for (var i = 0; i < Page_Validators.length; i++) {

      if (Page_Validators[i].validationGroup == validationGroup) {

        // call validator function

        var func = Page_Validators[i].evaluationfunction;

        Page_Validators[i].isvalid = func(Page_Validators[i]);

        if (!Page_Validators[i].isvalid) {

          isValidEntry = false;

          Page_Validators[i].style.visibility = '';

        }

      }

    }

  }

  return isValidEntry

}

 

So how does this work? The function returns a boolean value that suggests whether the validation is correct. The function goes through all the page validators, and selects the ones which belong to the specified validation group – this way we ensure only validators needed to be invoked are actually checked.

 

Later, we just call the ValidateEntry JavaScript function before calling the method that does the persisting – in my example, before calling a pagemethod that calls some server side method that does an insert in the db. The example is below:

 

First we have the controls that have the validators on them:

<td>

  <asp:TextBox MaxLength="50" ID="txtNewName" runat="server"

    Width="495px" ValidationGroup="NewEntityValidationGroup">

  </asp:TextBox>

</td>

<td>

  <asp:RequiredFieldValidator ID="valNewName" Text="*" ValidationGroup="NewEntityValidationGroup" runat="server" ControlToValidate="txtNewName">

  </asp:RequiredFieldValidator>

</td>

<td>

  <asp:TextBox ID="txtNewDescription" TextMode="multiLine" runat="server" Height="100px" Width="495px" ValidationGroup="NewEntityValidationGroup">

  </asp:TextBox>

</td>

<td>

  <asp:RequiredFieldValidator ID="valNewDescription" Text="*" ValidationGroup="NewEntityValidationGroup" runat="server" ControlToValidate="txtNewDescription">

  </asp:RequiredFieldValidator>

</td>

Then we have the pagemethod call with the call to the validation function (ValidateEntry):

 

function AddNewEntity() {

  if (ValidateEntry("NewEntityValidationGroup")) {

    var entityName = $get('<%=txtNewName.ClientID %>');

    var entityDescription=get('<%=txtNewDescription.ClientID %>');

    PageMethods.AddEntity(entityName.value, entityDescription.value, AddEntitySuccess, OnFailure);

  }

}

 

Lets analyze the function above – before we do any processing, we check all the validators, and only if the function returns true, we continue with the field value retrieval and call the pagemethod.

 

The best practice to use this type of validation would be to extract it to a new file and include the JavaScript file wherever it is needed.

 

If you want to incorporate this into your solution, feel free to go ahead and use the JavaScript function above, it is easy to integrate –just copy it to your solution, either to the page itself or to a JavaScript file and then just call it.

Currently rated 3.5 by 11 people

  • Currently 3.454545/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Comments

Add comment


(Will show your Gravatar icon)  

  Country flag


  • Comment
  • Preview
Loading




Contact

Development and Sales
ICodeFactory d.o.o.
Trg Marije Trandafil 24/2
21000 Novi Sad
Serbia, Europe
Phone: +381 (0)21 41 77 08
info[at]icodefactory[dot]com

Headquarter
T.C. Bagljaš, Lok. 11
23000 Zrenjanin
Serbia, Europe

Working hours
Monday - Friday
8am - 4pm (GMT+1)