Force Page Validation from Javascript
There have been those times wherein I needed to force page validation client-side. In these scenarios I want to avoid the annoying effort of writing a bunch of code to check for empty values or certain selections yadda yadda yadda...I also want to take advantage of all of the nifty ASP.NET validation controls that come with Visual Studio (i.e. RequiredFieldValidator, CompareValidator, etc).
In a high-octane Ajax enable web application manually invoking these validation controls to fire on the client instead of allowing .NET to manage their execution is crucial.
The last thing I want to do is write a bunch of code to check for certain values...this is a pain. It's much easier to wire up a .NET validator to a server control. So, it turns out that the way to execute page validation on demand from Javascript is by manually calling the Page_ClientValidate() function. It works like this:
- Create your server controls (the TextBox will be validated by a required field validator to ensure that a value has been entered by a user, and the Input:Button will be used to fire the Javascript SaveData() function):
<asp:TextBox ID="TextBox1" runat="server" />
<input type="button" value="Save" onclick="SaveData()" />
- Create your validation control and associate with the server control:
<asp:RequiredFieldValidator ID="Validator1" runat="server"
ControlToValidate="TextBox1"
ErrorMessage="You must enter a value into the textbox." />
- In Javascript call the Page_ClientValidate() function:
function SaveData() {
if (Page_ClientValidate()) {// Do something Ajaxie
}
}
Whala...it's that simple. The SaveData() function will fire and the validation error message will be displayed to the user. If the user did enter a value into the textbox, then your code is free to make whatever Ajax call that it needs to...this is high-octane...no server round trips!
Also, I recently learned that you the Page_ClientValidate() javascript function has an overload wherein you can pass the ValidationGroup that is assigned to a validator (if this has been defined), and the validation will only be executed for that group. Here's a link to the blog that I *learnt* that from:
http://magmainteractive.net/weblogs/post/Client-side-validation-with-AJAX.aspx
Comments