JavaScript DSL Because I’m Tired of Writing If.. If…If…

A little while ago a co-worker had expressed a dream of his to create some kind of language agnostic standard for validation. Without actually listening to what he meant by that, I set forth on doing this for JavaScript. I wanted to Lisp it up, as I am that kind of zealot. The idea was simple, provide a list like structure for describing the validation needs, but not make it a complete cluster *($#. I got the first part, not sure about the second. Essentially I wanted something like this:

 var rules =
    ('Username',
      ('is not empty' 'Username is required.')
      ('is not longer than' 7 'Username is too long.'))

Where ‘Username’ is the name of the property needing the validation, and the ‘7’ is the maximum length, and the last part is the error. But, seeing as this was JavaScript, I had to do something a little more rigid.

Now for what the rules would look like:

 var rules =
    ['Username',
      ['is not empty', 'Username is required.'],
      ['is not longer than', 7, 'Username is too long.']],
    ['Name',
      ['is not empty', 'Name is required.']],
    ['Password',
      ['length is between', 4, 6, 'Password is not acceptable.']]];

As you can see, the rules turn out to be very readable. On top of that, since it is only a list, converting a json based array to the rules should be pretty easy. The advantage of that would be the ability for a server response to contain the rules at which time the interpreter would match them to the methods. Thus providing a way to help with consistency of error messages, and constant values like in the password rule above. Something that is a pain in the #@@ some… all of the time.

The structure is fairly simple. [Property name [[validation need][extra parameters][error]…..[validation need][extra parameters][error]]] Essentially every property that is going to be validated can have n number of validation methods “attached” to it. Now one catch is that the object being validated has to have a matching “Property name”. Kind of falls into the “opinionated programming” side of things.

For this example, there will be three fairly generic validation methods. The methods either return null, or an error message. Over simplistic much?

 function isNotEmpty(toCheck, propertyName, error, rest) {
    return toCheck[propertyName] === '' ? error : null;
  };

  function isNotLongerThan(toCheck, propertyName, error, rest) {
    return toCheck[propertyName].length > rest[0] ? error : null;
  };

  function isBetween(toCheck, propertyName, error, rest) {
    var length = toCheck[propertyName].length;
    return (length < rest[0] || length > rest[1]) ? error : null;
  };

And here is an example of how to attach the english to methods:

 var methods = [
    ['is not empty', isNotEmpty],
    ['is not longer than', isNotLongerThan],
    ['length is between', isBetween]];

I created a pseudo method look up table to match a much more “english” name for the validation method needed. Not exactly brilliant, and is sort of cheating. What would be nice is to actually read the english, break it down, and create the functions on the fly. BUT this works for now. That whole english breakdown I’ll attack at some point. After all, this was a sort of thought experiment.

The interpreter takes in the rules, matches the method, and send the extra values if needed. For example,

   ['length is between', 4, 6, 'Password is not acceptable.']

Is matched to:

  isBetween(toCheck, propertyName, error, rest)

Where “rest” is the 4 and 6. Rest is a carryover from Commmon Lisp’s &rest. It’s a collection of things that will be broken down by the validation method. Just think of them as optional values.

 var length = toCheck[propertyName].length;
  return (length < rest[0] || length > rest[1]) ? error : null;

There are two parts to the interpreter, but the first part is merely rolling through the rules, and making a call to this:

  src.site.validation.validationInterpreter.createAValidationCall = function(propertyName, methods, innerRule, find, car, cdr, peek, sink) {

 //Find the method that matches the english phrase
    var methodPair = find(methods, function(method) {
        return car(method) === car(innerRule);
    });

 //In Closure the find method returns the whole matched "row", so I need the method which is the second column.
    var methodToUse = peek(methodPair);

    return function(obj) {
        var error = peek(innerRule);                           //error is the last index
        var values = sink(cdr(innerRule));                     //get everything but the error  
        return methodToUse(obj, propertyName, error, values);  //construct the validation call
    };
};

car, cdr, sink, peek? The *(&^ are those? First two are carry overs from Common Lisp too. Car is just taking the first item of a list, if there is one.

  (car '(1 2 3)) ;;  1

Cdr returns a new list that is everything but the first item.

  (cdr '(1 2 3)) ;; '(2 3)

Haskell refers to them as Head and Tail. Clojure has First, and Rest. ect. ect. ect.

sink is used to get all but the last item in the list. Everything but the kitchen sink. Eh? Eh? Sigh. (The code for them can be seen here.).

peek is actually just a parameter cover for the goog.array.peek method. It gets the last element of an array. Remember, the structure is very specific. [validation need][extra parameters][error] Because of this, it’s easy to break down each rule into its respective parts using simple array manipulation.

Now at this point I only have created the method list creator (“Interpreter”), and haven’t created anything for running the validation. However, the code below is a rough estimate of how that would work.

 var result = interpret(rules, methods);

 var toValidate = {'Username': '12345678', 'Name': '', 'Password': '123'};
  for(var i = 0; i < result.length; i++) { something.innerText += '\n' + result[i](toValidate); };

The glaring issue with that is that I’m not removing empty strings. Other than that, it works. The working example is in the example folder for this repository. The removal would be nothing more than using a map -> filter type method chain.

 var validationMesssages = goog.array.map(result, function(item) { return item(toValidate); };
  return goog.array.filter(validationMesssages, function(message) { return !goog.string.isEmptySafe(message); });

Or something like that… probably not exactly like that unless you’re in with the Closure, or are stuck with Jsomethingry.

jQuery Validate Date/Check If Is Date

Far as I can tell, and that’s pretty far even though I do wonder if you can actually measure telling in distance, there isn’t a method directly used for validating a date in jquery. I find this rather odd. Not odd like how people keep watching Uwe Bol movies, more like odd that no one has tried to make a time machine to prevent them from ever appearing.

Anyways, bad movies… horrible movies… worst movies of all time aside, there is a date checking method, just not directly in jquery. It’s actually in the jquery.ui.datepicker.js file which is part of the UI files. Basically I grabbed that file and used the parseDate method on it coupled with a try catch. After all, a failure in the parseDate method throws an exception, and we don’t like those. No we don’t. (Which begs the question as why it throws an exception instead of just returning a null date.)

function isValidDate(controlName, format){
    var isValid = true;

    try{
        jQuery.datepicker.parseDate(format, jQuery('#' + controlName).val(), null);
    }
    catch(error){
        isValid = false;
    }

    return isValid;
}

Very simple, and it works. You could ask why I didn’t just roll my own date method, and then I would ask you how ambitious do you think I am? Then you would punch me because I answered your question with a question like a complete tool bag. Then I would cry. And THEN I would answer your original question. Fact is, I trust that the method created for the DatePicker is in fact well tested, otherwise the whole jquery thing just isn’t worth trusting seeing as it’s a part of their core library. And that I just refuse to believe.

jQuery Validation: Adding Errors to the Error Containter… With Love!

Hello again, my wonderful audience, I have something great and fun planned for this post. If you read this post you might have been left wondering how to add custom messages to the error holder. It’s ok if you did, there’s nothing wrong with being confused all the time. It’s what makes you so adorable.

Say you have a form like this, and if you don’t I cry endlessly for your loss. My heart goes out to you.

<form id="ILoveEverythingForm">
    <div id="NotSoNiceThingsDiv" style="display:none;"></div>
	...
</form>

As you can see, there is an error div to hold mean things that we have to print out because the system just doesn’t like the user. As we both know, the user can’t help but be dumb. It’s just in his cute little nature. And that nature is just so darned cute.

Now let’s assume that you have something that sent back a bunch of mean messages when you tried to validate server side after all the cute client side validation was done. You might have a method to take in those jerk face messages. How do you display them in the bad place?

  function updateErrorDivContentWithLove(messages)
  {
    if(messages.length > 0)
    {
      var validator = jQuery('#ILoveEverythingForm').validate();

      for(var loopCounter = 0; loopCounter < messages.length; loopCounter ++)
      {
        validator.showErrors
        (
          {
             'SomeWonderfulElementName' : messages[loopCounter].Message
          }
        );
      }
    }
  }

Awwww kitties!

  

Only thing that may seem odd (And if it doesn’t, don’t worry you are still very special and loved in this world):

  'SomeElementName' : messages[loopCounter].Message

Not sure what element really needs to be here, basically anything in the form with a name tag. So if you’re good like I know you are, you have at least one element in that little old form with a name property set. I would say that this is pretty useless in situations where all the errors are shown in one div, as opposed to right next to the element, but that would be mean and I don’t do that.

Now I know you wanted something special from this post so I just wanted you to know that even though most of the world considers you hideous, I say you should be proud of being hideous because it makes you who you are. A unique miracle that only really has issues with dogs and small children. Embrace yourself in whatever way you take that!

Custom Data Annotations With MVC: How to Check Multiple Properties at One Time

Ok so maybe you read this post and you’re thinking to yourself, “I wonder if Diet Dr. Pepper really does taste like regular Dr. Pepper” which of course is silly because the ads clearly say it does. Now you should be asking yourself, “How do I check if two properties have the same value on a class with annotation when the property level ones only can check the one property’s value?” Kind of wordy way of asking that, but I get what you’re asking. Better yet, like usual, I have an answer.

Now what I can swear is that I was no where near the Baxter Building between 1-3 am on Saturday the 15th. I was in fact I was sleeping and have 20 witnesses that can testify. What I can’t swear is this is the best way to go about it but it seems to work AND make sense. It’s not common for me to come up with solutions that do both.

  [AttributeUsage(AttributeTargets.Class)]
  public class PropertiesMatchAttribute : ValidationAttribute
  { 

    public String FirstPropertyName { get; set; }
    public String SecondPropertyName { get; set; } 

    //Constructor to take in the property names that are supposed to be checked
    public PropertiesMatchAttribute(String firstPropertyName, String secondPropertyName )
    {
      FirstPropertyName = firstPropertyName;
      SecondPropertyName = secondPropertyName ;
    } 

    public override Boolean IsValid(Object value)
    {
      Type objectType = value.GetType();
      //Get the property info for the object passed in.  This is the class the attribute is
      //  attached to
      //I would suggest caching this part... at least the PropertyInfo[]
      PropertyInfo[] neededProperties =
        objectType.GetProperties()
        .Where(propertyInfo => propertyInfo.Name == FirstPropertyName || propertyInfo.Name == SecondPropertyName)
        .ToArray();

      if(neededProperties.Count() != 2)
      {
        throw new ApplicationException("PropertiesMatchAttribute error on " + objectType.Name);
      }

      Boolean isValid = true;

      //Convert both values to string and compare...  Probably could be done better than this
      //  but let's not get bogged down with how dumb I am.  We should be concerned about
      //  dumb you are, jerkface.
      if(!Convert.ToString(neededProperties[0].GetValue(value, null)).Equals(Convert.ToString(neededProperties[1].GetValue(value, null))))
      {
        isValid = false;
      }

      return isValid;
    }
  }
}

And then the use:

  [PropertiesMatchAttribute("Password", "ConfirmPassword", ErrorMessage = "Match the passwords, dumb--s.")]
  public class UserCreateModel
  {
     public String ConfirmPassword{ get; set; }
     public String Password { get; set; }
  }

Wasn’t so hard was it? Normally this would be the part where I degrade you for being bumb because you didn’t figure this out but I’m above that now. I guess it must be the holiday season or that I’ve been told by the board that I should be more gentle with my readers. Guess some were crying after reading some of my posts. Yeah whatever. Bunch of [Removed by Andre].

jQuery Validation – How to Use to Get Rid Of Even The Toughest Stains

So you want to use jQuery validation, huh?

What is it? Something that was added to the holy jquery site and is an easy way to validate input from users. Now this should in no way take over for server side validation, but it helps to at least catch a few things without having to send anything to the server. So how do ya do it?

Well to start, you need some files:

jquery-1.3.2.js and jquery.validate.js.

Now oddly enough the validation file isn’t hosted on the holy jquery site but how to use it is.

Ok now you have the files, what’s next? Well you need form, and I can do that for you.

So basically it’s a simple form with one input that is required.

jQuery(document).ready
    (
      function()
      {
        jQuery("#PrimaryForm").validate
        (
          {
            errorLabelContainer: "#ErrorDiv",
            wrapper: "div",
            rules:
            {
              FirstName :
              {
                required : true
              }
            },
            messages:
            {
              FirstName:
              {
                required : 'First Name is required.'
              }
            },
            onfocusout : false,
            onkeyup: false,
            submitHandler: function(label)
            {
              postSubmit();
            }
          }
        );
      }
jQuery("#PrimaryForm").validate

Real simple, just setting the validator to the primary form on the page.

 errorLabelContainer: "#ErrorDiv",

This sets the errors to show up in the ErrorDiv. Now this is optional, as you can have it show the errors next to the FirstName text box but personally I think that looks horrible. Setting up the ErrorDiv puts all the errors in one central location and allows for styling the actual div.

 rules:
 {
    FirstName :
    {
      required : true
    }
  },

This matches an element with the id of FirstName to the required rule, meaning that FirstName is required. Rocket science.

  messages:
  {
    FirstName:
    {
       required : 'First Name is required.'
    }
  },

If you can’t figure this out, I hear circus is hiring for the “World’s Dumbest Person”. You’ll fit in with Jub Jub the Dog Boy.

  onfocusout : false,
  onkeyup: false,

Basically this prevents the validation when leaving the textbox or on every key press. This is just another preference.

  submitHandler: function(label)
  {
    postSubmit();
  }

If the submit is successful, call this method.

But… BUT WHAT IF IT’S AN EMAIL?!??! WHAT WILL I DO???!?!?

Well for one, stop being such a child. And two, look here.

Some what different, as you can see it’s now email and there is one extra requirement in the rules:

  rules:
  {
    EmailAddress :
    {
      email : true,
      required : true
    }
  },
  messages:
  {
    EmailAddress:
    {
      required : 'Yo, email fool.',
      email : 'So not an email address.'
    },
  },

See? It has nice built in rule for email. Simple.

BUT WHAT IF I NEED A REGULAR EXPRESSION?!??! WHAT WILL I DO???!?!?

I swear if you don’t stop that, I’m turning this post around and going home.

Fine here it is.

  jQuery.validator.addMethod
  (
    "isZipCode",
    function(value, element)
    {
      return value.match(new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/));
    }
  );

Just have to create a method and “add it” to the validator itself. And then there’s the use:

  rules:
  {
    ZipCode :
    {
      required : true,
      isZipCode : true
    }
  },
  messages:
  {
    ZipCode:
    {
      required : 'For the love of me, enter a zip code!.',
      isZipCode : 'Serioulsy?  Do you know what a zip code is?'
    },
  },

Woo hoo right?

Don’t do it… Don’t you yell.

But what if one input depends on another?

Much better. Well that’s not as hard as it may seem and here’s the example.

  rules:
  {
    InputB :
    {
      required :
      {
        depends : function(element) { return jQuery('#InputA').val() != "" }
      }
    }
  },

As you can see, you can change how the required method works by adding in a depends handler. Works out pretty well.

Yes I will show you how to make sure two inputs match. I swear you ask for a lot.

  rules:
  {
    Password :
    {
      equalTo : "#ConfirmPassword"
    },
  },

Couldn’t be easier unless I wrote it out for you. Wait, I did.

So here you’ve either learned a bit about jQuery validation or have just spent the last few minutes drooling uncontrollably. Either way, I’m done with this post and you’re left to do whatever it is you do, you sick f—.

Side note: I haven’t actually been to Htmlgoodies since eh college? but wow did that place sell out. How fitting that an introduction to html page now looks like it was designed by someone just starting out… in the 90s.