Tag Archives: webdesign

Required Field Validator for Checkbox in ASP.NET

Unlike other form fields, ASP.NET does not have a required field validator control for checkbox. You have to roll your own with a custom field validator. Quick and easy example straight from Microsoft:

Checkbox Control

<asp:Label Font-Bold="true"
  ID="lbl_CheckBoxPrint"
  Text="I have the ability to print from this computer or device:"
  AssociatedControlID="CheckBoxPrint" runat="server" />

<asp:CheckBox
  id="CheckBoxPrint"
  runat="server"></asp:CheckBox>

Custom Validator

<asp:CustomValidator
  id="cust_CheckBoxPrint"
  runat="server"
  ErrorMessage="Print Capability"
  OnServerValidate="ValidatePrint">* required</asp:CustomValidator>

Do not forget to put the validation function name in the OnServerValidate attribute.

Validation Code

Sub ValidatePrint(ByVal source As Object, ByVal args As ServerValidateEventArgs)
        args.IsValid = (CheckBoxPrint.Checked = True)
End Sub

Not that hard, but not quite as easy as just adding a required field validator control.

Complete Code

  <asp:Label Font-Bold="true"
    ID="lbl_CheckBoxPrint"
    Text="I have the ability to print from this computer or device:"
    AssociatedControlID="CheckBoxPrint"
    runat="server" />

<asp:CheckBox
  id="CheckBoxPrint"
  runat="server"></asp:CheckBox>

<asp:CustomValidator
   id="cust_CheckBoxPrint"
   runat="server"
   ErrorMessage="Print Capability"
   OnServerValidate="ValidatePrint">* required</asp:CustomValidator>

'This goes in a script block or on a code behind page
Sub ValidatePrint(ByVal source As Object, ByVal args As ServerValidateEventArgs)
        args.IsValid = (CheckBoxPrint.Checked = True)
End Sub

Modal Confirmation Dialog on Form Submit: Javascript, jQuery UI, and Thickbox Varieties

jQuery files updated June 23, 2010. Because Thickbox is no longer supported, I may have to drop its example to update the jQuery files in the future.

If you liked this post, you might also like the jQuery.ajax and jQuery.post Form Submit Examples with PHP post.

I wanted to make a nice modal dialog box that would confirm submission of a form. And, specifically, it had to ask if their e-mail address was correct that they listed on the form. Typos, particularly transposed letters, cause a number of undeliverable e-mails. Making matters worse, sometimes by the time they get to the ‘Submit’ button, the all important e-mail field is no longer in view. Yes, despite the web developer’s best efforts, people still manage to type in their own e-mail incorrectly. I’ve done it. We’re all human.

I already knew about the javascript 1.0 method of ‘return confirm’ but I wanted more control over the look and feel. As an added requirement, I wanted to use Thickbox since I already had that loaded into the app. I don’t like throwing in a bunch of js files for every little nuance. If I can use what I already have, it makes the app much leaner.

So, I Googled it. I only found partial solutions. I wanted to go all the way and have the modal box pop up whether the user hit ‘Submit’ or whether they hit enter on the keyboard in as many browsers as possible (hint: IE). Maybe I didn’t look hard enough, but I ended up creating the solution on my own.

Here are three examples (including a complete demo) of a form submission confirmation dialog. One each for just javascript, the jQuery UI dialog box, and Thickbox.

Javascript 1.0

Echo back a message for fun:

<?php if (isset($_POST['emailJS'])){
 echo "<p class='message'>Javascript 1.0 worked!!! Your e-mail address is " .$_POST['emailJS'];
 echo "</p>";
 }?>

For pure javascript it’s painfully straightforward:

<form id="testconfirmJS" name="testconfirmJS" method="post" onsubmit="return confirm('You entered your e-mail address as:\n\n' + document.getElementById('emailJS').value + '\n\nSelect OK if correct or Cancel to edit.')">>
<fieldset>
<legend>Javacript Return Confirm</legend>

<p><label for="email">E-mail:</label><br />

<input id="emailJS" type="text" name="emailJS" value="" /></p>

<p><input type="submit" value="Submit" /></p>

</fieldset>
</form>

And you get something that looks like this:
javascript confirm box

Low overhead, not too much strain on the brain but pretty plain vanilla. And boring. Let’s do something a little fancier.

jQuery UI

The jQuery UI library is awesome. Loads of flexibility and customization available and they hand you everything you need. For this solution we have to load in an additional stylesheet (you can download a custom ready-made css), the jQuery base js, and the jQuery UI js. The jQuery UI site allows you to customize its js file to include only the parts you will use.

And, because this example uses Thickbox which is no longer supported, the jQuery core and jQuery core have not been updated to the latest versions. If you are not using Thickbox, use the latest version of jQuery.

<link rel="stylesheet" type="text/css" href="css/blitzer/jquery-ui-1.8.2.custom.css">

<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.2.custom.min.js"></script>

The form is untouched for this approach, but we do have to add some js to the document itself and an additional div element that will hold the contents of our modal box.

Here the we set some parameters for the dialog box including what the buttons should say and do. Then a little jQuery is added so that the e-mail is displayed in the box and the box opens on submit allowing the user to hit the ‘Submit’ button or the enter key.

        $(function(){
                // jQuery UI Dialog    

                $('#dialog').dialog({
                    autoOpen: false,
                    width: 400,
                    modal: true,
                    resizable: false,
                    buttons: {
                        "Submit Form": function() {
                            document.testconfirmJQ.submit();
                        },
                        "Cancel": function() {
                            $(this).dialog("close");
                        }
                    }
                });

                $('form#testconfirmJQ').submit(function(e){
                    e.preventDefault();

                    $("p#dialog-email").html($("input#emailJQ").val());
                    $('#dialog').dialog('open');
                });
        });

Echo back a message for fun:

<?php if (isset($_POST['emailJQ'])){
 echo "<p class='message'>jQuery UI worked!!! Your e-mail address is " .$_POST['emailJQ'];
 echo "</p>";
 }?>

The form is pretty clean and the div containing the text for the dialog box can be placed anywhere on the page.


<form id="testconfirmJQ" name="testconfirmJQ" method="post">
<fieldset>
<legend>jQuery UI Modal Submit</legend>

<p><label for="email">E-mail:</label><br />

<input id="emailJQ" type="text" name="emailJQ" value="" /></p>

<p><input type="submit" value="Submit" /></p>

</fieldset>
</form>

<div id="dialog" title="Verify Form jQuery UI Style">
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 0 0;"></span> You entered your e-mail address as:</p>
<p id="dialog-email"></p>
<p>If this is correct, click Submit Form.</p>
<p>To edit, click Cancel.<p>
</div>

Using this method you get a much prettier result:
jQuery dialog box

Thickbox method

The ever helpful and massively adaptable Thickbox was easily coded to do this as well. Thickbox also requires its own stylesheet and js along with the base jQuery file. Many apps have this already loaded since Thickbox is so wildly popular.

<link rel="stylesheet" type="text/css" href="css/thickbox.css">

<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="js/thickbox-compressed.js"></script>

As with the jQuery UI method, we add some js to the document to put in the e-mail from the form, open the Thickbox, and instruct the buttons on what actions to take when clicked.

        $(function(){
                //Thickbox

                $('form#testconfirmTB').submit(function(e){
                    e.preventDefault();

                    $("p#TB-email").html($("input#emailTB").val());
                    tb_show('Verify Form Thickbox Style','TB_inline?height=155&amp;width=300&amp;inlineId=TBcontent');

                });

                $('input#TBcancel').click(function(){
                    tb_remove();
                });

                $('input#TBsubmit').click(function(){
                    document.testconfirmTB.submit();
                });
        });

Echo back a message for fun:

<?php if (isset($_POST['emailTB'])){
 echo "<p class='message'>Thickbox worked!!! Your e-mail address is " .$_POST['emailTB'];
 echo "</p>";
 }?>

The form is also clean for this method and a div is added for the Thickbox content.

<form id="testconfirmTB" name="testconfirmTB" method="post">
<fieldset>
<legend>Thickbox Modal Submit</legend>

<p><label for="email">E-mail:</label><br />

<input id="emailTB" type="text" name="emailTB" value="" /></p>

<p><input type="submit" value="Submit" /></p>

</fieldset>
</form>

<div id="TBcontent" style="display: none;">
<p>You entered your e-mail address as:</p><p id="TB-email"></p>
<p>If this is correct, click Submit Form.</p><p>To edit, click Cancel.<p>
<input type="submit" id="TBcancel" value="Cancel" />
<input type="submit" id="TBsubmit" value="Submit Form" />
</div>

The Thickbox, generically styled (the default styling actually), looks like this:
Thickbox modal confirm box

Three flavors for confirming on form submission. Enjoy.

Recommended:

Demo

Test Drivin’ Safari 4

I gave Safari 4 a whirl on both Mac and PC. I like it. It brings much of the cool stuff from iTunes into the browser. Cover flow is fun and fresh in a browser. The Top Sites with the page previews is an upscale rip off of Chrome and, really, it’s a good feature for any browser.

Cover Flow
Safari Cover Flow
Top Sites
Safari Top Sites

Safari 4 is great for casual browsing and general perusing of the code but web development work stills needs the robustness of the Firefox plugins. Firefox is so ahead of the curve for web developers and I’m so used to it’s fantastic toolbars and debuggers that I don’t know if anyone will catch up. Granted the Safari 4 Web Inspector on the pre-packed Developer toolbar is nifty. Gotta love the ‘Resources’ tab. Nice visual of the weight of each loaded item. The included scripts debugger is handy and a much needed accessory in every browser.

Did I mention Safari 4 is fast? It is. That my biggest complaint with Firefox. It can be slow to render. Maybe that will improve with FF 3.5. Still, the trade off at this point is worth it. Bottom line is Safari 4 is great for browsing and the Web Inspector is a must ‘once over’ tool for developers.

FYI, Lifehacker has a great article on the latest browser speed tests.

Google Analytics API Login Authentication with ColdFusion

You might also like the ColdFusion and Google Analytics: Getting Out What You Put In post.

Updated 08-02-2009: Replaced this line:

<cfset accountXML = callApi("https://www.google.com/analytics/feeds/accounts/#urlEncodedFormat(form.Email)#",loginAuth) />

with this:

<cfset accountXML = callApi("https://www.google.com/analytics/feeds/accounts/default",loginAuth) />

My Hooking into Google Analytics with ColdFusion post received a suggestion from Raymond Camden that authentication and token acquisition could be done via cfhttp for access to Google Analytics information. So, here it is again with authentication built in. I set this up with a email/password form but you could easily hard code the email and password in if you so desired.

1. Prompt for email and password of Google account that has access to Google Analytics data. This is an all-in-one example so the form submits back to its own page and processing continues.

<form action="GAwithCFlogin.cfm" method="post">
Google email <input type="text" name="Email" /><br />
Password <input type="password" name="password" /><br />
<input type="submit" />
</form>

2. Authenticate the credentials with Google.

<cfset loginAuth = googleLogin(form.Email,form.password) />

The googleLogin function sends the email/password combo along with the service and source values as URL parameters required by Google to Google’s client login URL via a post request. The source parameter is a Short string identifying your application, for logging purposes. This string should take the form: “companyName-applicationName-versionID” according to Google. You can put in your company name or whatever name you want followed by the rest of the convention Google suggests. Example: yourcompanyname-analytics-1.0. The default start and end dates are also set here.

<!---dates for one full year of stats (default)--->
<cfset startdate = DateFormat(DateAdd("d",-365,CreateDate(Year(Now()),Month(Now()),Day(Now()))), "yyyy-mm-dd") />
<cfset enddate = DateFormat(DateAdd("d", -1, Now()),"yyyy-mm-dd") />

<cffunction name="googleLogin" access="public" returntype="string">
	<cfargument name="email" type="string" required="yes" default="">
	<cfargument name="password" type="string"required="yes" default="">
    <cfargument name="gaLoginUrl" type="string" required="no" default="https://www.google.com/accounts/ClientLogin">

    <cfset var loginAuth = "" />

    <cfhttp url="#arguments.gaLoginUrl#" method="post">
        <cfhttpparam name="accountType" type="url" value="GOOGLE">
        <cfhttpparam name="Email" type="url" value="#arguments.email#">
        <cfhttpparam name="Passwd" type="url" value="#arguments.password#">
        <cfhttpparam name="service" type="url" value="analytics">
        <cfhttpparam name="source" type="url" value="yourCompanyName-analytics-1.0">
    </cfhttp>

	<cfif NOT FindNoCase("Auth=",cfhttp.filecontent)>
		<cfset loginAuth = "Authorization Failed" />
	<cfelse>
		<cfset loginAuth = Mid(cfhttp.filecontent, FindNoCase("Auth=",cfhttp.filecontent) + (Len("Auth=")), Len(cfhttp.filecontent)) />
	</cfif>

    <cfreturn loginAuth />
</cffunction>

What should come back is a long string of authorization token values. There are several but we only need the Auth token. If it’s not in there, we send back “Authorization Failed.” If it’s in there, we strip it out and return it.

3. Get the accounts associated with the email. There can be more than one set up in Analytics.

<cfset accountXML = callApi("https://www.google.com/analytics/feeds/accounts/default",loginAuth) />

The email account is appended onto the Google URL and a get call is made from the callApi function with the loginAuth token attached as a header value.

<cffunction name="callApi" access="public" returntype="string">
    <cfargument name="gaUrl" type="string" required="yes">
    <cfargument name="authToken" type="string" required="yes">

    <cfset var authSubToken = 'GoogleLogin auth=' & arguments.authToken />
    <cfset var responseOutput = "" />

    <cfhttp url="#arguments.gaUrl#" method="get">
        <cfhttpparam name="Authorization" type="header" value="#authSubToken#">
    </cfhttp>

    <cfset responseOutput = cfhttp.filecontent />

    <cfreturn responseOutput />
</cffunction>

The header value must be in the form of Authentication: GoogleLogin auth=DF3843483…(it’s kind of long but you get the idea). This authentication is different form AuthSub Proxy authentication used in my previous post.

4. Clean up the XML that returned so we can use XmlSearch() and other handy functions available in ColdFusion. For some reason the atom specification of the XML file bungles those functions up. We need to remove the xmlns nodes from the feed element and remove the dxp prefixes. Do a cfdump on the XML before and after two lines of code used to tidy them up to seed what happens.

<cfdump var="#accountXML#">

Then roll through the accountXML with to grab all the profiles and toss them into an array so we can loop through them later.

<!---remove dxp: prefix from nodes that have it--->
	<cfset accountXML = accountXML.ReplaceAll("(</?)(\w+:)","$1") />
	<!---Strip xmlns from feed element--->
	<cfset accountXML = REReplaceNoCase(accountXML,"<feed[^>]*>","<feed>") />

	<cfset entryNodes = XmlSearch(accountXML, '//entry/') />

	<cfset profileArray = ArrayNew(1) />

	<cfloop from="1" to="#ArrayLen(entryNodes)#" index="num">
		<cfset entryStruct = StructNew() />

		<cfset entryStruct.id = entryNodes[num].id.XmlText />
		<cfset entryStruct.title = entryNodes[num].title.XmlText />
		<cfset entryStruct.tableId = entryNodes[num].tableId.XmlText />

		<cfloop from="1" to="#ArrayLen(entryNodes[num].property)#" index="i">
   			<cfswitch expression='#entryNodes[num].property[i].XmlAttributes["name"]#'>
    		    <cfcase value="ga:accountId">
       		     <cfset entryStruct.accountId = entryNodes[num].property[i].XmlAttributes["value"] />
     		   </cfcase>
      		  <cfcase value="ga:accountName">
    		        <cfset entryStruct.accountName = entryNodes[num].property[i].XmlAttributes["value"] />
 		       </cfcase>
		         <cfcase value="ga:profileId">
		               <cfset entryStruct.profileId = entryNodes[num].property[i].XmlAttributes["value"] />
	            </cfcase>
	            <cfcase value="ga:webPropertyId">
	                <cfset entryStruct.webPropertyId = entryNodes[num].property[i].XmlAttributes["value"] />
	            </cfcase>
	        </cfswitch>
	    </cfloop>

		    <cfset arrayAppend(profileArray,duplicate(entryStruct)) />

		</cfloop>

5. Loop through the profiles, grab the page views and visitors, and tally them up for all profiles.

<cfset totalpageviews = 0 />
<cfset totalvisitors = 0 />

		<cfloop from="1" to="#ArrayLen(profileArray)#" index="num">
	    	<cfset reqUrl = "https://www.google.com/analytics/feeds/data?ids=" & profileArray[num].tableId & "&metrics=ga:pageviews,ga:visitors&start-date=" & startdate & "&end-date=" & enddate />

	 		 <cfset statsXML = callApi(reqUrl,loginAuth) />
	                <!---Tidy up the XML again --->
	 		 <cfset statsXML = statsXML.ReplaceAll("(</?)(\w+:)","$1") />
			 <cfset statsXML = REReplaceNoCase(statsXML,"<feed[^>]*>","<feed>") />

			 <cfset metric = XmlSearch(statsXML, '//metric/') />

			 <cfset pageviews = metric[1].XmlAttributes["value"] />

                         <cfset visitors = metric[2].XmlAttributes["value"] />

			 <cfset totalpageviews = totalpageviews + pageviews />

                         <cfset totalvisitors = totalvisitors + visitors />

			 <p><strong>Profile:</strong> <em>#profileArray[num].title#</em> Pageviews: #NumberFormat(pageviews, ",")# Visitors: #NumberFormat(visitors, ",")# </p>

		 </cfloop>

		<p><strong>Total pageviews:</strong> #NumberFormat(totalpageviews, ",")#</p>
                <p><strong>Total visitors:</strong> #NumberFormat(totalvisitors, ",")#</p>

All done. Thank you Raymond Camden and Alex Curelea. Alex got me pointed in the right direction with his post Using the Google Analytics API – getting total number of page views. And, as I mentioned at the get go, Raymond Camden made the suggestion of using the login as some of his examples have done in the past.

Recommended Reading

Download

Information on Google’s Authentication for Installed Application ClientLogin and the Google Analytics Data API ClientLogin Username/Password Authentication.

Helpful ColdFusion books include the all-in-one ColdFusion MX 7 WACK with tons of good information even if you’ve moved up to CF8. Crazy as it seems, Adobe decided to break up ColdFusion 8 books into three volumes: Volume 1: Getting Started, Volume 2: Application Development, and Volume 3: Advanced Application Development. You may be able to pick up a used copy in good condition. Follow the book link to Amazon and look for used copies underneath the books title.

Latest mag obsession “Practical Web Design” aka “.net”

I have to hand to the Brits; they are into web design and standardization like nobody’s business. Web design and development is a moving target. I have been to the expensive conferences and events. Loads of great and inspiring info. Problem is you need something that you can refer back to and use as a resource. And, something that is here and now, tangible, tactile, and moving as fast as web evolution itself. I’m talking mags.
.net mag
I got my hands on a copy of the UK produced and published “Practical Web Design” (known as “.net” in Great Britain) magazine at Borders and have read every word twice. It’s like carrying around the enthusiasm and electricity of a conference in my pocket(book). This is what web designers need. A constant flow of practical and applicable information. It keeps you motivated and relevant. It doesn’t hurt that I have met many of the contributors and advisory panels members at the aforementioned conferences. They are picking the top and, IMHO, the most credible talent to fill the pages.

Now for the bad news. It’s expensive here in the US (over $130/yr) at the current exchange rate. I’ll keeping picking it up a copy at a time to spread out the pain, but I love it anyway.