JQuery validation not working for checkbox group - asp.net

I'm having trouble getting JQuery validation to work with a set of checkboxes. I'm generating the checkboxes using an ASP.NET checkboxlist, and I've used JQuery to set the 'name' attribute to the same thing for each checkbox in the list. Here's the code that gets written to the browser. I'm setting the 'validate' attribute on the 1st checkbox to set the rule that at least one checkbox must be selected. The JQuery validation works for all other elements on the form, but not for the checkbox list. I'm also using a JQuery form wizard on the page which triggers validation for each 'page' of the form, so I don't have control over how the validation is called.
<input id="ContentPlaceHolder1_MainContent_AreaOfInterest_0" class="ui-wizard-content ui-helper-reset ui-state-default" type="checkbox" value="Famine" name="hello[]" validate="required:true, minlength:1">
<label for="ContentPlaceHolder1_MainContent_AreaOfInterest_0">Famine</label>
<br>
<input id="ContentPlaceHolder1_MainContent_AreaOfInterest_1" class="ui-wizard-content ui-helper-reset ui-state-default" type="checkbox" value="Events Volunteer" name="hello[]">
<label for="ContentPlaceHolder1_MainContent_AreaOfInterest_1">Events Volunteer</label>
Any ideas on what's going wrong? There are lots of examples of JQuery scripts that will do the validation, however I'm trying to avoid this as I'm generating the checkboxlist server side by a custom control so that it can be re-used across different pages that may or may not have JQuery enabled. I'm trying to enable the JQuery validation whilst being as unobtrusive as possible, so that pages will still work even if JQuery is disabled.
Here are the relevant JQuery inclusions and JQuery initialisation script for the form wizard. I'm not using any initialisation code for JQuery validation:
<script type="text/javascript" src="../js/formwizard/js/bbq.js"></script>
<script type="text/javascript" src="../js/formwizard/js/jquery.form.js"></script>
<script type="text/javascript" src="../js/formwizard/js/jquery.form.wizard.js"></script>
<script type="text/javascript" src="../js/formwizard/js/jquery.validate.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#form1").formwizard({
validationEnabled: true,
focusFirstInput: true
});
});
</script>

Using JQuery to set the 'name' of each checkbox to a consistent value 'breaks' the checkbox list in .NET (I thought this would happen). Basically it's too complex to use the JQuery forms wizard and JQuery validate with a customised .NET checkboxlist. They aren't really compatible. .NET needs to have different names for each of the checkboxlist inputs, which doesn't play well with JQuery validate (certainly not when also using the form wizard). I'm going to try switching off JQuery validation in the forms wizard (it has this option) to see if the form wizard will work OK with the validation (including client-side validation), of the .NET validators. I'll post back my results! Think I tried doing this originally and the form wizard wasn't working correctly, which is why I started using JQuery validation with the form wizard, so my current solution is just to just remove the multi-page form (the form's not too too long without this), to simplify things, and just rely on .NET validation (client and server side). Someone made the point that a multi-page form can leave the user wondering exactly how many field are left to fill, while at least a single page form allows them to see the fullness of what they need to complete!
This is the form wizard I am/was using:
http://thecodemine.org/

Related

How to call HTML5 form.checkValidity during form.onSubmit in WebForms?

How can i override, or extend, the standard WebForms WebForm_OnSubmit JavaScript function?
I am using HTML5 input types in an ASP.net WebForms web-site. The user-agent (e.g. Chrome, IE, Firefox) already correctly handles data sanitization, alternate UI, etc.
Normally, when a user clicks an <input type="submit"> button, the User-Agent will halt the submit, and show UI to indicate to the user that their input is going to be invalid:
The problem with WebForms is that it does not use a Submit button. Instead, everything can be done through a JavaScript postback, rather than submitting the form:
<asp:LinkButton ID="bbOK" Text="Save User" runat="server" OnClick="bbOK_Click"></asp:LinkButton>
Which, when rendered into client HTML, becomes a call to the JavaScript:
WebForm_DoPostBackWithOptions(...)
With the really long form being an Anchor tag:
<a id="Really_Long_Thing_ctl00_bbOK"
href='javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$MainContent$VistaToolbar$ctl00$bbOK", "", true, "", "", false, true))'>
Save User
</a>
This means that the user-agent never gives the user a prompt that an entered element is invalid.
Even though the form is not being "submitted", it does still trigger an onsubmit event. I can manually trigger the HTML5 form validation using something like:
isValid = form.checkValidity();
Ideally i would hook that event in my ASP.NET WebForms site:
Site.master
<form runat="server" onsubmit="return CheckFormValidation(this)">
<script type="text/javascript">
function CheckFormValidation(sender)
{
//Is the html5 form validation method supported?
if (sender.checkValidity)
return sender.checkValidity();
//If the form doesn't support validation, then we just assume true
return true;
}
</script>
Except that the WebForms infrastructure deletes my onsubmit method handler, and replaces it with its own:
<form id="ctl01" onsubmit="javascript:return WebForm_OnSubmit();" action="UserProperties.aspx?userGuid=00112233-5544-4666-7777-8899aabbccdd" method="post">
So my own submit call is ignored. It appears that delving into WebForm_OnSubmit leads down a rabbit hole of ASP.NET WebForms validation infrastructure:
function WebForm_OnSubmit()
{
if (typeof(ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false)
return false;
return true;
}
which calls the function:
var Page_ValidationActive = false;
function ValidatorOnSubmit()
{
if (Page_ValidationActive) {
return ValidatorCommonOnSubmit();
}
else
{
return true;
}
}
which calls, which calls, which uses, which checks.
Just want HTML5 form validation with WebForms
The issue is that WebForms has a huge infrastructure for checking a form before submitting, and displaying errors to users through a standardized mechanism (and entire infrastructure that i do not use). It takes over the onsubmit event of forms, and it doesn't (necessarily) use an <input type="submit"> in the process.
What can i do to convince ASP.NET WebForms web-site to let the User-Agent validate the form?
See also
HTML validation and ASP.NET Webforms
How do I get Client-side validation of ASP.NET page to run?
Trigger standard HTML validation (form) without using submit button?
MSDN Magazine: Better Web Forms with HTML5 Forms
The web forms infrastructure deletes the handler because you attempt to add it directly on the element in the visual design environment, and web-forms is not designed to work this way.
Trapping the on-submit handler is easy, you just need to think a little creatively.
Whenever your trying to deal with anything like this in a web-forms environment, you have to learn to think about solutions that come after the web-forms page rendering pipeline. If you try to find a solution that works directly inside the web-forms engine, then web-forms will win every-time.
You can reproduce my exact test case here if you need too, or you can pick out the bits you need and re-use as required.
Step 1
Create a NEW web-forms project in C# (You can do it in VB if you want, but I'm putting my examples as C#), once your project has been created, right click on your application references, go into NuGet and install JQuery.
It is possible to do this with out JQuery, and just use native methods, but it's Sunday and I'm being lazy today :-)
Step 2
Add a new web-form to your project (using add new item) and call this 'Default.aspx', onto this form add some text, a text box a button and a label.
your code should look similar to:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="jsvalidation.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
Please enter your name :
<asp:TextBox ID="txtName" runat="server" data-jsname="username"></asp:TextBox>
<asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" />
</div>
<asp:Label runat="server" ID="lblResult">...</asp:Label>
</form>
</body>
</html>
Then press F7 (or double click on the button) to go to the code behind editor for your form.
Step 3
Add your code for the button handler into your code behind. If your doing things exactly the same way as me, your code should look similar to this:
using System;
namespace jsvalidation
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if(Page.IsPostBack)
{
lblResult.Text = "Well hello there " + txtName.Text;
}
}
}
}
At this point you can test things work by pressing F5, and what ever you enter (or don't enter) in the text box, should appear with the message in the label below when you press the submit button.
Now we have a basic web-forms set up, we just need to intercept the form submit.
Step 4
As I said a moment ago, you need to think outside the web-forms box.
That means you need to run your intercept AFTER the page has been rendered and sent to the browser.
All of the JS that web-forms injects into the mix is usually executed before the page output is allowed to proceed, which means before the opening body tag.
In order to get your code to run after it, you need to put your script at the END of the html output so that it runs last.
add the following code just before the closing body tag, but AFTER the closing form tag
<script src="/Scripts/jquery-2.1.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('form').submit(function() {
var uninput = $('input[data-jsname="username"]');
var username = uninput.val();
if (username == "")
{
alert("Please supply a username!");
return false;
}
});
});
</script>
The more astute among you, will notice straight away that I'm not calling the HTML5 validation API, the reason is I'm trying to keep this example simple.
Where I check the username value is the important part.
All that matters is the anonymous function in which I perform the check returns true or false. (True is the default if you DON't return anything)
If you return a false, you'll prevent the post back taking place, thus allowing you to use whatever JS code you need to make the form fields change using the HTML5 validation API.
My personal preference is to use bootstrap (See the syncfusion free e-book range for my Bootstrap 2 book, and soon to be released Bootstrap 3 book), where you can use special markup and css classes in the framework such as "has-errors" to colour things appropriately.
As for the selection of the components using JQuery, well there's 2 things here you need to pay attention too.
1) You should NEVER have more than one form on a web-forms page, in fact if I remember correctly, your app will fail to compile if you do, or at the most it'll certainly throw an exception at run-time.
2) Beacuse you only ever have one form, then you can be very safe in making the asumption, that a generic 'form' selector in JQuery will only ever select your main form (Irrespective of the ID, name, lack or size thereof) and adding an onsubmit handler to it, will always attach this after web-forms has don'e it's thing.
3) Beacuse web-forms can (and usually does) mangle ID names, it's generally easier to use 'data attributes' to add custom bits to your tags. The actual ASP.NET js side validation does this exact same trick itself to allow JS code and .NET code to happily co-exist in the same page. There are ways to tell .NET how to name the ID's but generally you have to set lots of options in lot's of places, and it's very easy to miss one. Using 'data attributes' and the JQ attribute selector syntax is a much safer, easier to manage way of achieving the same thing.
Summary
It's not a difficult task, but I have to admit, it's not one that's immediately obvious if your not looking outside the fence that web-forms builds around you.
Web-forms is designed for rapid application development, primarily for devs used to the desktop win-forms model. While web-forms still has it's place these days, for new greenfield apps I would recommend looking at other options too, esp ones that build on the foundations that the new HTML5 specifications are trying hard to lay down and get right.

unobtrusive javascript validation not submitting form in asp.net mvc 3

I'm using the latest RC with asp.net mvc 3, and have turned on unobtrusive javascript validation and added the necessary scripts to the page. All of the validation works perfectly, but when I try to submit the page, it simply doesn't post. If I turn unobtrusive javascript off in the web.config without making any other changes, everything works perfectly fine.
Here's my scripts I'm using:
<script src="#Url.Content("~/Scripts/jquery-1.4.4.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
Inside the page it's just a standard form using Html.BeginForm().
Might help to put some more information so we can try to repro this.
The form won't post if something is invalid. So chances are a field is not valid, but you maybe you don't have the display set up properly. Did you make sure to add a call to Html.ValidationMessageFor(...) for each form field? That renders a span where the client validation message appears.
This also happens when hidden fields are required. Such a simple thing, but it has caused me quite a bit of stress.

Easiest/Best Hide/Show Client Side Hide/Show for ASP.NET

I have a DropDownList and a TextBox on a Page. When the user chooses the "other" option in the DropDownList I want to display a TextBox just to the right of it. I do not want to use the traditional PostBack technique. I want this interaction to be client side.
I am aware that I can get a get a reference to the DOM element and set its style to "display:none" or "display:". What I am looking for is something that is built into the ASP.NET framework for handling something like this. I mean, in jQuery this is as simple as $('controlID').hide. Is there a Control Extender that can do this? Is jQuery part of the ASP.NET framework yet?
jQuery will be/is distributed with VisualStudio/ASP.NET MVC, though I wouldn't call it part of the framework. I think that you can feel free to use it and trust that it will be supported.
Note that Microsoft has said that they will be using the main line of development for jQuery so the code itself won't be any different than you can download from jQuery.com, except perhaps for built-in Intellisense.
EDIT: To set up your functionality download the code from jquery.com. Put it in your scripts folder, or wherever you store javascript stuff. Add a script reference for it to your page. Use jquery to add an onchange handler to your dropdown list and when the value of the dropdown list is other show the textbox, otherwise hide it. The example below assumes that other isn't the default selection. If you are using runat="server" controls with MasterPages or inside UserControls, you'll need to adjust the names in the javascript functions to account for the name mangling that ASP.NET does. Probably simpler to give them unique CSS classes and reference them using the ".class" notation rather than "#id" notation.
<script type="text/javascript" src="...pathtoscript../jquery.1.2.6.js"></script>
<script type="text/javascript">
$(document).ready( function() {
$("#DropDownListID").bind('change', function() {
if (this.options[this.selectedIndex].value == 'other')
{
$("#TextBoxID").show();
}
else
{
$("#TextBoxID").hide();
}
});
});
</script>
...
<select id="DropDownList">
<option value='first'>First</option>
...
<option value='other'>Other</option>
</select>
<input type='text' id='TextBox' style='display: none;' />
You could also use the asp.net client side framework(via the scriptmanager) to get a reference to the element. But then you still have to use the normal DOM manipulation.
$get('<%= myDropDown.ClientID %>').style.display = 'none';
Just make sure you have the script manager referenced.
For something so simple, I wouldn't think it is worth referencing jquery, but maybe you've got bigger plans ;-)

Using Javascript With ASP.Net controls

Is there a best practice when it comes to setting client side "onclick" events when using ASP.Net controls? Simply adding the onclick attribute results in a Visual Studio warning that onclick is not a valid attribute of that control. Adding it during the Page_Load event through codebehind works, but is less clear than I'd like.
Are these the only two choices? Is there a right way to do this that I'm missing?
Thanks!
Eric Sipple
**just a pre-note on the answer: HTML validation in VS is often BS. It complains about stuff that works IRL, even if that stuff is bad practice. But sometimes you gotta bend the rules to get stuff done.
Every ASP.NET page (2.0 and greater) comes with a ClientScriptManager. You use this to register javascript from server side code. You can pass in javascript that registers events on controls after the page has loaded, when the HTML controls on the page are all present in the DOM.
It presents a single, unified place on pages to dynamically add javascript, which isn't a bad thing. It is, however, awfully ugly.
In this time of the death of the ASP.NET server control model, you might want to set events the way they will be in the future of ASP.NET MVC. Grab a copy of jQuery and add it to your website. You can then easily register your events thusly:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("controlId").bind("click", function(e) { /* do your best here! */ });
});
</script>
</head>
<!-- etc -->
</html>
You can add the events through Javascript to the HTML elements that you want. This is the cleanest way, since it doesn't mix the server&client technologies. Furthermore, this way many handlers can be registered to the same event (in contrast to the onclick attribute).
Basically, the code would be
document.getElementById('myLovelyButtonId').attachEvent('onclick',doSomething)
for Internet Explorer and
document.getElementById('myLovelyButtonId').addEventListener('click',doSomething,false)
for other browsers. (doSomething is an event handler - JavaScript function). These calls should be made in the window load event handler
Consider reading the advanced event registration article on Quirksmode for further info.
Also, consider using a library like jQuery. This way, the statement will become
$('#myLovelyButtonId').click(
function doSomething () {
alert('my lovely code here');
});
Setting the value for WebControl.Attributes["onclick"] is okay. If ASP.NET needs a client-side click handler, it will concatenate the values, delimited by semi-colon.
Fix grammatical or spelling errors.
Clarify meaning without changing it.
Correct minor mistakes.
Add related resources or links.
Always respect the original author.

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