jQuery Validation in ASP.NET Pages - asp.net

I am using jQuery and jQuery.validate plugin to validate ASP.NET pages, since I found jQuery Validation plugin better than ASP.NET validation controls.
I have used This validation code for Login and simultaneously for other pages like register and many others.
//.NET code
Dim jsValidate As String = String.Format("Validators.validateLogin('{0}','{1}');", _
txtUsername.ClientID, txtPassword.ClientID)
btnLogin.Attributes.Add("onclick", jsValidate)
//javascript code
Validators.validateLogin = function(txtUsername, txtPassword) {
$('#aspnetForm').validate();
$('#'+txtUsername).rules('add', {
required: true
});
$('#'+txtUsername).rules('add', {
required: true
});
}
Now the problem I am facing is if I have multiple controls on a page which require or not require validation. How to handle that situation. Bcoz once someone clicked on Login button it starts validation function and on pressing on some other button in some other control, it stuck with current validation. I wish if jQuery validation plugin can handle some groups like ASP.NET validationGroup, it could be a lot easier. Anyone have suggestions?
Thanks in Advance

You might try overloading CSS classes as validation groups. Basically you could filter out the controls whose class didn't match a specific pattern and only validate against those. Kind of a hack but it might just work for you.

Related

Custom TextBox Control with built-in client-side validation

I have a textbox in my application which has multiple validation on it e.g. RequiredFieldValidator, RegexValidation and CustomValidation. My page has several similar textboxes. So I just copy-paste and change id and controltovalidate properties and it is working.
Since similar tbxs are going to be used on another page as well, I think it would be nice to create my own custom TextBox control with built-in validation.
Here are two approaches I have found and tried:
1: Implement from IValidator perform my custom validation in Validate Method. As shown here: Self-Validating TextBox But it does not show how to implement client-side validation.
2: Create custom control that derives from TextBox and add asp.net built-in validators I need. As shown here:Custom TextBox. I tried the code and it works server/client side.
I like the first approach but don't know how to implement client-side validation. I know I need a client-side js function. I can do that. I know how to include my js file using Page.ClientScript class but don't know how to integrate all together and make it work.
I can create a UserControl or the second approach above but for now I am specifically looking to learn and implement client-side validation from custom control.
I am using Asp.Net 2.0. Thanks for any suggestions.
Well, you're right, you can always implement your custom server control that derives from TextBox and automatically associates a couple of validators. But usually you won't create custom controls as far as it is not explicitly needed and then through several different projects. For having client-side validaton you usually need JavaScript, but note that most of the ASP.net validation controls have their client-side validation already built-in (i.e. required field validators, range validators,...). Others (like the custom validator) allow to hook in your custom javascript.
An approach that sounds more reasonable to me is to have your TextBox controls as they are on your ASP.net page/usercontrol and to associate the validators from your code dynamically at runtime. Say in your OnInit event, you call a function RegisterRequiredValidators passing in a list of TextBoxes. I'm just thinking aloud:
public override void OnInit(...)
{
...
RegisterRequiredValidators(
txtFirstname,
txtSurname,
txtAge
}
...
}
public void RegisterRequiredValidators(params Control[] textBoxes)
{
//execute the logic of creating and attaching validators
}
That's just a stupid example, just to explain the context. In theory you can evolve this concept to register any kind of validators. We do something similar at work, by abstracting this in form of "rules" which ultimately are being rendered as ASP.net validators on the front-end.

Can I assume asp.net form's ID always being the same?

I want to submit a simple asp.net form in jQuery
can I assume
$("form[0]").submit()
always works, cross browser?
You mean something like this
$("#aspnetForm").submit()
Something like above would work cross browser as you said
The code you pasted is cross browser too. It won't work on ANY browser so maybe that counts as cross browser :-) just a joke
No, you can't assume this. $("form[0]").submit() will submit the first form on the page. However, you can have more than one form on an ASP.NET page, though only one of these forms can be a server-side form (with runat="server" attribute).
If what you want is to submit the server-side form on an ASP.NET page then I think the best way would be to do it in code-behind by registering a script. It's a bit more hassle, but should always work (and when there is no server-side form it will detect it). Something like this:
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (this.Form != null)
{
string js = String.Format("$('#{0}').submit()", this.Form.ClientID);
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Submit", js, true);
}
}
These will:
$("#aspnetForm").submit()
or
var theForm = document.forms['aspnetForm'];
theForm.submit()
If you know that this code will be triggered by an input or button element within the ASP.NET form, or if you can select a known input or button element within the ASP.NET form, you can use input.form.submit();.
Usage examples
this.form.submit();
or
$("#some_input_or_button").get(0).form.submit();
Although reading the input.form/button.form property does not use jQuery, it is at least as cross-browser since jQuery itself does this.
Benefit: This method allows you to avoid dependence on the form ID generated by ASP.NET's internals without having to add any extra wiring server-side.

Raising javascript event from an ASP.NET user control and handling in ASP.NET page

In an ASP.NET page I have a user control and I want to perform some action within it using javascript. When that action is complete I want to raise an event (again in javascript) to be picked up by the containing ASP.NET page (again in javascript).
The reason I want to do this is because I have more than one user control on the page and I need the action performed in one user control to instantiate an action in another user control without doing a postback.
Does anyone know how to do this?
Many thanks.
Hi and thanks for the response.
What I'm trying to do is create some form of encapsulation. So if the javascript code does something in one user control that user control shouldn't know of the impact else where. It would raise an event in javascript which can be picked up by asp.net page rendered javascript which can in turn call a javascript method in another user control if it needs to.
The idea here is also to eliminate any need for a postback.
Hope this expains it better.
I think the simple way to implement what you are describing, is to forget about JavaScript events, and just supply a "callback" function to the user-controls.
The way i would implement it, would be to expose a public property on the user control, which takes the name of this JavaScript "callback-function". The user-control is then responsible for calling this function after it has finished its client-side job.
So the page that uses the user-controls will have to implement this JavaScript "callback-function", and then supply the name in properties to the user controls.
Makes sense?
You can simply run the javascript you need from the rendered HTML of your user control.
Click Me
By the sounds of things you want to create some form of controller in JavaScript. When the page loads each of your controls register with the controller. Then an action in one of your controls runs a function on the controller, which does something with the controls registered with it.
Your JavaScript could be as simple as:
var oControls = new Array();
doSomething = function() {
for(var i=0;i<oControls.length;i++) {
var oControl = document.getElementById(oControls[i]);
oControl......
}
}
So you need to register your control by using ScriptManager in your user controls render method.
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "Startup", String.Format("oControls.push('{0}');", ClientID), True);

Elegant way to combine ASP.NET validation with JQuery

How can I best combine JQuery with ASP.NET client side validation model?
I've generally avoided implementing ASP.NET validation model because it always seems overkill for what I was doing. For the site I'm working on now I'm just collecting non critical user data and only need somewhat basic validation. I dont want messages appearing in the DOM or anything like that. I've always found it hard to get that to look right anyway.
But I need now to implement something a little more elegant. What I want to take advantage of in JQuery is clever search expressions like 'tell me if at least one of these checkboxes is checked'. I'm new to JQuery, but I think this is about 1 line of JQuery and a lot more complicated in the traditional ASP.NET model.
So I want to take full advantage of JQuery's abilities but not completely undemine ASP.NET's validation model.
My best approach so far is this (which pretty much goes behind the back of ASP.NET):
$('#<%=btnJoinMailingList.ClientID %>').bind('click', function(event) {
if (...) {
alert("You must enter a name");
return false;
}
return true;
});
What's a better approach here? Are there any recommended plugins for JQuery ?
PS. I don't want to use MVC model. I'm trying to create a very 'RAD' site and dont have time to delve into that fun new stuff yet.
ASP.NET has many validation controls, one of them is the CustomValidator.
You can give it a custom JavaScript function that uses jQuery and returns true or false via argument. You can use this control to display the error message automatically, or just run the jQuery code and handle the display manually.
Aspx:
<asp:CustomValidator ID="CustomValidator1" runat="server" Display="None"
ClientValidationFunction="checkTextareaLengths">
</asp:CustomValidator>
JavaScript:
function checkTextareaLengths(source, args){
args.IsValid = true;
$('textarea').each(function(){
if($(this).text().lenght > 400)
args.IsValid = false;
});
}
ASP.NET webforms and jQuery's validation model is very, very similar, IMHO, in that both are client-side and implementing one of them does not necessarily undermine the other. The only real difference would be that, behind the scenes, ASP.NET validators will cause the Page.Validate() method to returns false if you have an unvalidated field.
You may opt to hand-roll your own validation controls, and then cause the same behavior, but as you yourself have stated, that might be overkill.
jQuery also has its own Validator plugin which you might want to look at: http://docs.jquery.com/Plugins/Validation/Validator.
ASP.NET validator is a span with additional attributes.
With jquery you can acces all validators on the page or filter they by any criteria
supported by jquery. To force validation via javascript call ValidatorValidate function.
For example:
function validate_step(step_element) {
// find all validators on step_element and force validation
var validators = $(step_element).find("span[controltovalidate]");
var stepIsValid = true;
validators.each( function() {
ValidatorValidate(this); stepIsValid &= this.isvalid;
});
return stepIsValid;
}

jQuery Validation plugin and ASP.NET validators Web Forms

I would really like use the jQuery Validation plugin in my ASP.NET Web Forms application (not MVC).
I value jQuery validation for the Richer UI experience I can provide the end user and I have some requirements to highlight the invalid fields using a red border (css).
I value asp.net validators because they run the validations not only on the client but on the server so that I don't open various security vulnerabilities to any user who is clever enough to turn off javascript in their browser.
So I am looking for a nice clean way to integrate these two technologies.
The best I can come up with is to have all ASP.NET validators set to enableclientscript=false and repeat the validation rules on the client in jQuery and on the server as asp.net validators but I can already see some challenges with this approach.
In the end I found the lowest friction way to achieve highlighting with asp.net validators and jquery was not to use the jQuery Validation plugin but to use the simple line of jquery which follows (note that the exact syntax will vary depending on how you layout your forms):
<script type='text/javascript'>
$("input[#type=submit]").click(function() {
$('span.validationerror:hidden').parent().parent().find('input').removeClass('inputError');
$('span.validationerror:visible').parent().parent().find('input').addClass('inputError');
});
</script>
You can use asp.net and jquery validators together with no problem... even on the same control... you just need to set CssClass for the control so that jquery can find it... and then you add OnClientClick="return $('#aspnetForm').valid();" to your submit button(s).
Be sure and include the usual jquery library and jquery.validate.js and add a document ready function of course, etc.
This might help!
http://www.delphicsage.com/home/blog.aspx?d=205
If you are serious about validation, I would look into something like Peter Blum's validators (http://www.peterblum.com/Home.aspx) as they should be able to do everything you want and more. They don't use JQuery, but remember the whole point of JQuery is to save developer time - the end user doesn't know or care whether you are using JQuery or not if the overall effect is the same.

Resources