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!

SqlAlchemy: Self Referential Many To Many

Ok this was just plain annoying to figure out. A couple of misteps and a few F—! later I finally got it. So the situation is this:

You have a table for user to ignore users. So it’s basically a many to many where both sides of the relationship are the user table. The creation might look like this:

class User(Base):
    __tablename__ = "User"
    id = Column(String(36), primary_key=True, default=lambda : str(uuid1()))

Basically a table named User and it has a primary key. Yee haw. Now for the hanging table:

class UserIgnore(Base):
    __tablename__ = "UserIgnore"
    id = Column(String(36), primary_key=True, default=lambda : str(uuid1()))

    ignored_by_id = Column("ignored_by_id", String(36), ForeignKey("User.id"))
    ignored_by = relationship("User", backref="ignored_list",  primaryjoin=(User.id == ignored_by_id))
    ignored_id = Column("ignored_id", String(36), ForeignKey("User.id"))
    ignored = relationship("User", backref="ignored_by_list",  primaryjoin=(User.id == ignored_id))

Basically you need a table/object with two columns: ignored_by_id (The one doing the ignoring) and ignored_id (The one being ignored). And at this point the word “ignored” should look like it’s not even a word anymore because I’ve typed it too much already.

Now the relationship is made using two different properties:

    ...
    ignored_by = relationship("User", backref="ignored_list",  primaryjoin=(User.id == ignored_by_id))
    ...
    ignored = relationship("User", backref="ignored_by_list",  primaryjoin=(User.id == ignored_id))

As you can see, I had to hit it from both angles. (I’d hit it! LOLOLOLHARHARORAALROARH) Not only how to describe the relationship from ignorer to ignoree (Those are words now) but also in reverse. That way I can have a constructor like this:

    def __init__(self, user, userToIgnore):
        self.ignored_by = user
        self.ignored = userToIgnore

And also if I do something like this:

    UserIgnore(_user, _user2)
    UserIgnore(_user2, _user)

I can have it all save correctly just by adding _user to the session or saving _user id at some point.

Also both those lists will be added to the User object without having to do anything further.

someUser.ignored_list

or

someUser.ignored_by_list

Yay for that.

Talent Versus Persistence

Let me tell you about my one time mentor Dan, and no Dan isn’t a fictional character to make a point. Dan (Cousineau) is a multi time NASKA national champion, quite a few gold medals in world competition, not to mention an accomplished BJJ practitioner. I had the pleasure of being one of his students for many years and being able to compete for the Dragon Karate Team.

Now with that out of the way, I’ll attempt to get to a point.

For the most part, when I was competing (post 1996) the prototypical national champion for weapons (Or forms for that matter) was somewhere between 5-6 to 5-10 and 150 to a buck seventy. As forms became more “flashy”, it was very helpful to be light and compact. (Examples like Jon Valera or Mike Chatr.. Chatura… Chat and later on Steve Terada and the legendary Kim Do) Then there was Dan. Dan was 6’1″ and (sorry Dan ) 240ish. He was about as far from prototypical that one could get… and he still won constantly.

I think the word “talent” gets thrown around a lot without people really knowing what it means. In my ten or so years of competition, I saw a lot of “talent”. There were people that were just plain gifted. It came so easy to them that it was just like breathing, but they weren’t the best. They weren’t the ones taking home National Championships. Why? Because they weren’t persistent.

Dan wasn’t a champion because he was gifted. I’m not sure anyone ever said he was “talented”. Excellent? Yes. Elite? For sure. But “talented”? That’s just an insult. Wait… what? Insult?

You see, I think when people say “talented” what they actually mean is “lucky” or “just born with it”. I think it’s used almost as an excuse by people that don’t want to work for anything. There was nothing “talented” about Dan. He was a hard worker. He was the guy that ran a school, worked another job, and still managed to practice with any free time he had. (Even outside before work) He was the guy that would be training on Saturday and Sunday mornings. (In fact one thing he used to say when we trained on Sunday mornings was “Everyone else you’re competing against is sleeping right now.”) It wasn’t something he was given by some god or genetics. It was pure time, work, and persistence. He never stopped, he never gave up, and he never took it easy. He lived by the mantra of “Second place is first loser.” To call him “talented” is to ignore the countless hours he gave to his training. The weekends of traveling to anywhere from California to Germany. The overwhelming drive it took to keep competing. That is what made Dan elite. That is what made people like John Valera and Steve Terada champions. They were the ones that pushed on where most would fold. In the world of the elite, there are only the persistent. The gifted ones were left far behind.

Now the question you might have right now is: Is this going somewhere? And yes I say. Yes it is.

I think the “talented” frame of mind is too prevalent in world of programming. I think most programmers are too comfortable to just slap “talented” on anyone who excels at programming. Now it’s true, some people are just smarter than others. For every Dan Cousineau in the world, there are five others that fit the prototypical programming mold. However, I’m willing to bet most truly great programmers, “gifted” or not, live to program. They spend a lot of time outside of work programming. When other people are out getting drunk, they are perfecting their craft. They are the ones that push past the fear that most have when moving into new territory and just do it. They persist. They don’t give up. They don’t make excuses. They do.

If you want to be a truly great programmer, or hell even slightly better than average like me, you have to do. You can’t sit around in a pity party going on about how someone else has it better. You can’t make excuses for why other people are excelling. You can’t just blindly slap the “talented” word on someone and console yourself when you see that person getting out of your reach.

Or you can. But just remember that out there, somewhere, there’s a Dan Cousineau busting his a– while you sit around wading in your tears.

The choice is yours.

HTML Thing… Label versus Div or Span When it Comes to Inputs

One of the things that PyCharm tells me over and over again when it comes to HTML and Inputs is that I’m just not using those ——- — labels you —- ——- excuse for a ——- programmer. (Ok, so I might be paraphrasing a bit) Now for the most part it isn’t the end of days if you use a span or div instead. No kittens will be harmed either way. However, and I admit I must be slow for not seeing this, but labels do have one advantage as told by the dub see three:

The label element does not render as anything special for the user. However, it provides a usability improvement for mouse users, because if the user clicks on the text within the label element, it toggles the control.

Quite simple put, if the user clicks the label or the input, it will put focus on the input. Yeah so not earth shattering but for people with stupid hands like me, it just gives me a better chance of actually clicking a textbox than the massive Evony Online ad right next to it.

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?

Simple Property Merge for Python Objects

Not sure if this is useful to other people, but then again if I cared that would make me human.

So here’s a quick way to merge two objects in python:

def mergeObjectProperties(objectToMergeFrom, objectToMergeTo):
    """
    Used to copy properties from one object to another if there isn't a naming conflict;
    """
    for property in objectToMergeFrom.__dict__:
        #Check to make sure it can't be called... ie a method.
        #Also make sure the objectobjectToMergeTo doesn't have a property of the same name.
        if not callable(objectToMergeFrom.__dict__[property]) and not hasattr(objectToMergeTo, property):
            setattr(objectToMergeTo, property, getattr(objectToMergeFrom, property))

    return objectToMergeTo

This is a good example of how the whole dynamic addition of properties happens in Python. The objects in this example have a __dict__ property that is basically where the property/method/other stuff information is held in dictionary form. What does this mean? It means that if you use the setattr method you can then later call the property like you would normally.

  setattr(someObject, 'someProperty', 'some value')

  someObject.someProperty == 'some value

Knowing this is important as it allows you to really do some fun dynamic stuff that a lot of other languages just don’t allow.

I Have Found Python and I Am a Changed Man

Ok so maybe the title is full of sensationalism, but in some ways it’s true.

In the beginning there was Microsoft.

When I started programming at the unusually late age of 24, I was brought into the world by Microsoft. At the time, ASP was still in fair use and .Net was the new wonder drug and no one, not even Microsoft, could nail down what it was exactly. It was a miracle in a bottle, an olde time elixir. It would fix everything known and even unknown unknowns. Now personally, I had only really taken a liking to the style of C++. I preferred brackets to subs and never minded semi-colons. So you can imagine when I found out about “the C#” , I was all about it. Looking back now, it does seem sort of silly since there really wasn’t that much of a difference between VB.Net and C#, but d—-it I was going to get my semi-colons or here go hell come. Naturally this meant I would start a journey of 8+ or so years into the Microsoft frontier.

Have Carrot and Stick, Will Travel

I think one of the strongest suits of the .Net framework was Microsoft’s need to constantly improve it. Now these improvements weren’t overnight but it seems like they made a lot of improvements in relatively short time. Every version just seemed to have the answer to every question I didn’t know I needed to ask. It was like they were reading the mind of future me and adding features based on that mind. Yeah ok, it’s a little ego centric to suppose that future me was the only person asking for such things, but I’m cool with my version. I can still remember how annoyed I was that the place I was working for wasn’t going to invest in 2.0 for a while, thus keeping me from my coveted generics. (Pretty sure I said the word to the point it didn’t sound a like word anymore) And honestly, a little nerd rage was expected since I didn’t want to type every parameter as Object. I can also remember how in awe I was of Linq and some of the semi-functional programming concepts being introduced with 3.0/3.5. It seemed like as soon as I started to covet something new, BAM it was there. So really, I had no reason to ever stray from .Net because I was always well taken care of. Course then something changed and it was Microsoft’s fault.

There some things you can’t unsee

Remember that thing named Linq? Well Linq was more in line with the whole .Net mystique. It wasn’t just a way to manipulate lists, it was a whole lot more. With Linq came a few nice concepts like typed delegate, anonymous types, type inference on a much larger scale, extension methods, and a whole slew of other larger concepts like Entity Framework. It was kind of like taking a trip to the moon. Sure the whole moon thing is great, but the massive amount of new technologies that came from just getting there was where the real gold was. In the development of Linq, Microsoft had to come up with new stuff to even run the concept of Linq. At some level it was touted as Microsoft’s attempt to bring a more dynamic and functional look to C#. Now no one was claiming that C# was a functional language but d—ed if it didn’t try. After all, it’s not easy to make something more dynamic when the underlying technology is meant to be more static. Between being able to easily pass methods around like objects and using lambda expressions to simplify dealing with lists, it was a huge step forward and personally a large shift in my programming paradigm. (Yes I just used paradigm in my blog.) So where’s the catch? It’s simple, my eyes were opened to stunning new concepts. The use of Linq, lambda expressions, and Func/Action got me to start looking at programming as a whole in a different way. I wanted to be more dynamic. I wanted to start solving old issues using all this exciting stuff. And because of this I started expecting more and pushing .Net to the limits. For the first time in my programming career, the carrot was chasing me.

Model View what?

If Linq was the straw that broke the camel’s back, then MVC was the bus that ran it over by mistake. For years I had been in the standard world of Web Forms. Something that at one time seemed to be a beautiful bridge between the web and stand alone projects was now looking worse and worse. All the issues I had with Web Forms were now being magnified by the overall streamlined approach with MVC. It was such a strong double-hit between Linq and MVC that I just couldn’t ignore the outside world anymore. It’s sort of like that moment when you realize that your parents are human just like you. It makes you think that maybe everything you knew wasn’t actually the only way to do things. That maybe there’s something more out there. Maybe, just maybe, people didn’t eat cold pizza with syrup. This was the moment when I started wondering if there was something greater out there. (Just like Vger) Because I had never dabbled in anything outside of .Net (except a regrettable affair with PHP that still worries me that someday a little PHP will show up at my door claiming that I’m it’s dad) so this concept was brand new to me. Of course anyone who wasn’t completely clueless like me would have known that MVC had been used by things like Java for quite a few years. To makes matters ever worse, the poor camel was struck by a huge meteor named Javascript. Yes, I typed Javascript. With MVC came my heavy use of Javascript and it’s much fancier suit and tie JQuery, and guess what? I noticed that most of the cool new dynamic stuff for .Net was being used in Javascript all the while. I had shied away from Javascript for a long time since I was brainwashed into thinking it was evil. Just use post backs and server side code. Stay away from the language that we dare not speak its name. Problem was, it is almost a need when using MVC unless you want to refresh the page on any form post. Long story short, I was reeling from all this new information.

Every silver lining has a dark cloud

One thing that I didn’t like about most examples of how the model and view work together was the use of a dictionary to hold values that would appear on the view. I’ve never liked magic string programming so I naturally went with typed views. This meant that for every view I would have a model class working alongside to help pass values in a much more clean and safe way. The issue? A whole f–king lot of models. So much that it almost became a separate project in itself to hold all of them. Something just didn’t seem right about this. One of the nice things about C# is it’s more rigid feel to keep people from screwing things up (unlike the magic string theory). Problem was, for rapid development this just didn’t cut it. And let’s be honest, in the real world (unless you are the lucky few that have decent deadlines, i.e., top-end jobs) rapid is all we get. This left me in an uncomfortable place. We’re talking showing-up-to-school-naked-and-realizing-it’s-not-a-dream-this-time uncomfortable.

In time all things become clear

It would seem natural that if I liked all the more dynamic features of .Net and Javascript, I would possibly try to find a language that suited my needs. Well there’s an old thought in psychology: People don’t change unless something makes them. And as much as I’d like to say I braved the new world on my own, it really was more of a wake up call. While Microsoft has done a lot to add needed complexity to the framework, they continue to add far too much simplicity.

Not to long ago, some time after 4.0 was just about to go “gold” I read a couple articles on how easy programming was becoming in the .Net world, and how salaries for .Net were starting to drop. To sum it up, Microsoft has always tried to walk two lines: Cater to the more expert programmer AND the drag-and-drop programmer. Some nice examples would be from 2.0 in generics and update panels. Generics are still not understood by drag-and-drop programmers (as I have been shown on many occasions) but man they love their update panels. I mean it’s ajax without actually knowing anything about it. And I think this is where .Net is going to head. I think as elitist programmers we’d like to think that knowing design patterns and how to successfully design a streamlined system is important but honestly, it isn’t. And I’m saying this as a person who has had 7+ jobs jobs in the last 9+ years. Businesses want results. They don’t care if it costs them more in the end if you hack something together. I’ve never really met a company that thought that far ahead, and in some ways I can understand this. Getting to the market first can be a huge advantage. The “Just get something out now and worry about it later” mantra is prevalent in all walks of business. It’s hard to convince companies to take more time to develop a more solid system. Because of this, things like update panels and drag-and-drop design are still hanging strong which by proxy means having a solid understanding of how things work really doesn’t matter as much.

Though way too lengthy of a side bar, the point is that this is the event I needed to change. Because Python is a more fringe language but is used by some really good companies, it seemed like a reasonable switch… or at least something to experiment with. There is nothing really drag-and-drop about it.

If at first you don’t succeed…

I will admit that at first I was a little apprehensive about Python. It just didn’t seem to offer anything that C# didn’t… again at first. However, the more I used Python and Pylons, the more free I felt. All those years of pushing and expecting rigidity were washing away. Don’t me wrong, it took a while to really get how powerful Python can be. I mean stuff like adding properties to objects dynamically was nice, but that was also in 4.0. Passing methods like objects: C#… well at least with some restrictions. But with that being said, having options like that without the need for typing parameters and done so with a natural feel made it pretty well suited for web development. I’m not going to spout the virtues of Python and I’m pretty sure I’ve derailed this post quite a bit, but the moral of the story is simple:

There’s more out there than Microsoft/.Net. Now I realize that probably 2/5 readers (not a fraction but an actual guess on how many people will read this) will be thinking ‘DUH’ but this isn’t really written for people who know this already. This is written so that even Microsoft slappies like me can break free of a what I thought was the be-all and end-all, and really learn something new that isn’t new to .Net. I’ve built my career around .Net and have no doubt it will most likely be what I’m paid to use for a while. With that being said, there’s absolutely nothing wrong with trying new paths. Is Python the language to do this for you? I have no idea. Maybe it’s Ruby or (maybe(the(language(is(Lisp))))). That I can’t tell you. Only thing I can tell you is that you won’t know until you get out and try something new. You can’t possibly know what’s out there if you stay at the house that Microsoft built. In a world with too few eggs and a ton of baskets, you really can’t afford keep things the same.

Python: Added Folder By Namespace Won’t Import…. How To Make A Namespace.

Ran into this last night and it was giving me some issues. Basically, I added a folder (unitTest) and then some .py files to it. So my folder structure is something like:

pyzzazz/unitTest/validation/validationTest.py

Now one would assume you could do this:

from python.unitTest.validation.validationTest import someTestMethod

Problem was that the IDE (PYCHARM PLUG) was telling that it couldn’t see the unitTest namespace. After some nerd rage and searching, turns out that Python by nature doesn’t assume .py files outside of the main folder structure “belong” to it. The fix is simple though, add a blank __init__.py file to the folder. In my case, I added a blank __init__.py file to the unitTestFolder. Then and only then would the above namespace actually work. Here’s something on the __init__.py file

Are you a good programmer?

Something I’ve struggled with for a long time is how to define a good programmer. It’s not an easy task since it’s fairly subjective and there are a lot of different opinions on this. So many that you could say that this is just another drop in the bucket of irrelevancy known as byatool.com. But a post being pointless hasn’t stopped me before, so damned if it will stop me now.

The first question that a person might ask after reading the title of this page is: Do you really think the iPad will revolutionize the way schools handle reading material? And that is a fine question, but a bit off topic. So if I were to tell you what first question to ask, I would tell you to ask: Who the hell are I..you to ask you…me if I’m eh you’re? Oh f–k it, you get the picture. And the answer is: No one really. ANTI CLIMATIC!!!11oneonesevenone I’m not the world’s best programmer and won’t be winning the prestigious Byatool Programmer of the Year award. (And sadly I’m the only one in the running.)

But what I do have is a thirst… No, not that kind. I have thirst for knowledge.

Yeah yeah, I know “cliche”. However, the point is still there AND that’s only part of it. You see the thirst for knowledge is only a step, and it’s the easy one. Anyone can WANT to learn more, it’s taking the time to DO more. It’s not enough just to show up.

And I think it’s the doing that separates the real from the others. The doing is what separates. Separation is bound to doing. Doing separation. F–k where was I?

Look, despite what people tell you, life is not a box of chocolates otherwise we’d all be morbidly obese… and happy. Life is more like… one of those damned invisible fences with a shocking dog collar. Yeah you’re going to get zapped more often than not but at some point you’ll find that one area in the fence next to some kind of electricity tower that screws with the fence and allows you to break on through. Course most likely you’ve already lost most of your brain living so close to an electricity tower, so in reality you’re just breaking through to a life of madness and too dumb to know it.

But this was a really stupid analogy anyhow that doesn’t really make any f–king sense, so who cares?

The point, if there ever was one (which even I’m debating at this moment), is it is never easy. NEVER. It’s always a struggle. It’s always a pain in the a–, but it’s necessary. Why? Because it defines what a good programmer is. The struggle. Or more to the point, the perseverance. It’s so easy to just be happy with what there is now. You know, the old “If it ain’t broke, then let’s run the wheels off it” mentality that I think comes from an earlier generation. (Most likely the generation of any given current professional programmer)

Fact is, it’s OK to try something new. It’s OK to venture out into the unknown. And more importantly, YES YOU WILL BE SCURRED AND GET FRUSTRATED AT SOME POINT! This is completely natural. You aren’t stupid. It isn’t just you that feels that way. You aren’t a mutant because you are afraid you’ll fail. Sure I don’t doubt there are people out there that just naturally jump into the unknown, feel no fear, and figure it out in a day. That’s why they are billionaires and rare. For the rest of us relatively poor goofs, we have to deal with all of that AND perform.

Just remember, you have been conditioned by multitudes of areas to be afraid of change. Hell, even your brain fights change because it’s far more efficient to keep things as they are. It’s even a basic principle of existence: path of least resistance. What am I getting at? Just do it. Be that person. Fight your way into the new world.

Why? BECAUSE YOU’RE A GOOD PROGRAMMER. And if this doesn’t sound like you, well you know what you have to do. Well two things: One is to stop being such a baby and set a dentist appointment for your annual check up. Cavities are no laughing matter. Second is to stop letting your fears and comfort get in the way of your growth. After all, this is your (And I’m assuming) profession. It’s your job to be the best you can be.

It’s going to suck. It’s going to be nerve wracking. It’s going to push you to your limits… and you’re going to like it. Just remember to repeat to yourself, “F–k the noise, it can’t fade me.” (I’m not exactly sure what that means but it sounds tough.)

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.