MVC3, Entity Framework, jQuery… Everything example

How would you like to have a project that has these features?

Dependency Injection
Entity Framework 4.0 with POCO
Inversion of Control with Castle
The IResult
jQuery
jQuery Ajax Posts
jQuery Custom Css
jQuery Validation
Mocking with Rhino Mocks
MVC 3/Razor
MVC Annotation Based Validation
What I call the Repository Pattern
Unit Tests - Integration With Entity Framework
Unit Test - MVC Controller Actions

And more s--t I can't think of right now!

What’s the price of this gem? Just your time which is worth nothing!

Where can you find it? Right here!

Requirements:

Visual Studios 4.0
Mvc 3
To open the solution and do a search and replace on "Tutorial" to set your directory paths.
A real f--king need to learn!

Act now, operators aren’t in existence since this is hosted on a website, but if they were they would be standing by!

Disclaimer:

This may or may not hit you with a wave of awesome. Be prepared for the worse case awesome scenario. I am in now way responsible for any heart stoppage due to the shock and awe power of the project.

jQuery Validation with Multiple Checkboxes

So this one is done on request and because I am a kind of merciful god I will grant this request.

For those bullet point programmers:

Now when I say validation, I mean the validation plugin. and this example is built using concepts in this post.

Here’s the markup:

 
<form id="formCheckBoxValidation" method="post" action="checkboxValidation.html">
	<input type="checkbox" id="checkBoxList" name="checkBoxList" value="One">
	<input type="checkbox" id="checkBoxList" name="checkBoxList" value="Two">
	<input type="checkbox" id="checkBoxList" name="checkBoxList" value="Three">
	<input type="checkbox" id="checkBoxList" name="checkBoxList" value="Four">
	<input type="checkbox" id="checkBoxList" name="checkBoxList" value="Five">
	<br />
	<input type="submit" id="buttonCheckBoxValidation">
</form>
<div>
	<div id="divError" name="divError" style="display:none;"></div>
</div>

<form id="formCheckBoxValidationDifferentName" method="post" action="checkboxValidation.html">
	<input type="checkbox" id="checkBoxListOne" name="checkBoxListOne" value="One">
	<input type="checkbox" id="checkBoxListTwo" name="checkBoxListTwo" value="Two">
	<input type="checkbox" id="checkBoxListThree" name="checkBoxListThree" value="Three">
	<br />
	<input type="submit" id="buttonCheckBoxValidationDifferentName">
</form>
<div>
	<div id="divErrorDifferentName" name="divErrorDifferentName" style="display:none;"></div>
</div>

For this example I’m actually presenting two examples(Say ‘example’ again, I dare you, I double dare you m—erf—er, say ‘example’ one more God d–n time!): If the checkboxes are linked by id and if the checkboxes are not linked at all. There is actually a difference. You see, if they share the same id, the required method can be used since it will treat them all as the same element and therefore if even on is checked, there is a value. Otherwise, you have to check all the checkboxes to see if at least one is checked. (Yeah, that made total sense.)

Here’s the check checkboxes method:

//Add a method to the validator that checks to see if at least one of the
//  three checkboxes specified are checked.
jQuery.validator.addMethod(‘atLeastOneChecked’, function(value, element) {
	var checkedCount = 0;

	if (jQuery(‘#checkBoxListOne’).is(‘:checked’)){
		checkedCount += 1;
	}

	if (jQuery(‘#checkBoxListTwo’).is(‘:checked’)){
		checkedCount += 1;
	}

	if (jQuery(‘#checkBoxListThree’).is(‘:checked’)){
		checkedCount += 1;
	}

	return checkedCount > 0;
});

Oooooh baby.

Now for setting up the validation:

//This is for the first checkbox area where every checkbox has the same id causing them
//  to be a group and therefore the default required works.
var validationRules = new Object();
validationRules['checkBoxList'] = {required:true};

var validationMessages = new Object();
validationMessages['checkBoxList'] = {required:'at least one has be checked.'};

jQuery('#formCheckBoxValidation').validate({
	errorLabelContainer: '#divError',
	wrapper: 'div',
	rules: validationRules,
	messages: validationMessages,
	onfocusout: false,
	onkeyup: false,
	submitHandler: function (label) {
		alert('hooray');
	}
});

//This is for the second checkbox area where every checkbox has a different name
//  and therefore the atLeastOneChecked method must be used.
validationRules = new Object();
validationRules['checkBoxListOne'] = {atLeastOneChecked:true};

validationMessages = new Object();
validationMessages['checkBoxListOne'] = {atLeastOneChecked:'at least one has be checked.'};

jQuery('#formCheckBoxValidationDifferentName').validate({
	errorLabelContainer: '#divErrorDifferentName',
	wrapper: 'div',
	rules: validationRules,
	messages: validationMessages,
	onfocusout: false,
	onkeyup: false,
	submitHandler: function (label) {
		alert('hooray');
	}
});

In the words of Q-Bert: @#$% yeah!

jQuery Validator: Build Rules and Messages Dynamically

Ok so here’s your typical code for the jQuery Validator:

  jQuery(ELEMENT_FORM).validate({
    errorLabelContainer: ELEMENT_ERROR_DIV,
    wrapper: 'div',
    rules: {
      textboxEmailAddress: {
        required: true,
        email: true
      }
    },
    messages: {
      textboxEmailAddress: {
        required: ERROR_EMAIL_ADDRESS_REQUIRED
      }
    },
    ....

As you can see, the elements like “textboxEmailAddress” are hard coded in there which means if that name changes in the markup, this breaks. So the question is: How do I script the rules and messages so that I don’t have to hard code the element names?

Sorry was just waiting for you to finish you question. Ok, here’s the answer and it has to do with how great Javascript is as a language. (And oddly enough a trick I got from Python)

  var validationRules = new Object();
  validationRules[ELEMENT_TEXTBOX_EMAIL] = {required:true};

  var validationMessages = new Object();
  validationMessages[ELEMENT_TEXTBOX_EMAIL] = {required:ERROR_EMAIL_REQUIRED};

  jQuery(ELEMENT_FORM).validate({
            errorLabelContainer: ELEMENT_ERROR_DIV,
            wrapper: 'div',
            rules: validationRules,
            messages: validationMessages,
            ....

Where ELEMENT_TEXTBOX_EMAIL is a constant somewhere. How does this work? Well because the way dynamic languages like Javascript and Python work, objects can be treated like dictionaries which means you can add properties to them the way you would add a record to a dictionary:

  someObject['somePropertyName'] = 'hi';

is just like:

  someObject.somePropertyName = 'hi';

In fact I’m pretty sure the new Dynamic keyword in C# works in the same manor.

Now you could be a annoying and point out that replacing textboxEmailAddress with ELEMENT_TEXTBOX_EMAIL is still hard coding, and I would agree… to a point. The constant does two things:

1) Removes a “magic string” from your code.

2) Makes it really easy to update that string if the element name/id is changed in the HTML. Having only to look at one place to replace is a lot easier than 1+ places.

So there, smarty pants. What you gots to say now?

jQuery Validator: Adding a Custom Method

File this one under “Posted to take less time to find the answer”:

If you’re using jQuery Validator and the built in validation methods just aren’t cutting, there’s a way you can add your own method to the validator itself. For this example let’s start some pretend time. Uhg I said pretend time not f–ked up fantasy time… Really, a horse? Really?

Now that we have that clear: Let’s pretend you have a form with three textboxes and you want to make sure one and only one is filled out. This doesn’t exactly fit the built in methods. Now you could try using the “required” method and replace it with a delegate. Could do that, but it ‘s  actually trickier than it sounds due to how required method actually works.  So what’s an easier way? Just add a method to the validator:

    jQuery.validator.addMethod('correctCountFilled', function(value, element) {
        var fullCount = 0;
        if(jQuery('#someTextBox1').val().length > 0){
            fullCount +=1;
        }

        if(jQuery('#someTextBox2').val().length > 0){
            fullCount +=1;
        }

        if(jQuery('#someTextBox3').val().length > 0){
            fullCount +=1;
        }

        return fullCount == 1;
    });

Then the call is done lika dis:

  ...

  rules: {
            someTextBox1: {
                correctCountFilled:  true  //This is the name of the method added and what it expects to come back when called to be valid.
            }
        },
  messages: {
            someTextBox1: {
                correctCountFilled: 'Some error message like pointing out how yours is a superior intellect.'
            }
        },
  ...

As you can see, the method returns false if all are empty or more than one is filled in. The method call on the validator expects “true” to be valid, so anything but one textbox being filled in will trigger the error message. Fairly easy, huh? Now go forth, be fruitful, and don’t multiply by mistake.