jQuery .validate – what does optional really mean?

When you look customising validation rules and/or handlers for the jQuery validate plugin, you run across a lot of code that looks like this:

return this.optional( element ) || !/Invalid|NaN/.test( new Date( value ).toString() );

So obviously, that means “Don’t bother checking this field if it’s optional”, right? Wrong!

There are two important things you need to know about jQuery validate’s optional() function:

  1. It is NOT telling you whether the field is optional. It is just telling you whether the field is empty.
  2. It returns false if the field is NOT empty, and it returns the string “dependency-mismatch” if the field IS empty.

If you’re quietly thinking “WTF?” at this point, you’re not alone. The semantics do make a bent kind of sense once you know what’s going on, though. Obviously there’s no point checking any validation but “required” on an empty field. So the code above is saying “If this field is OK, it will be either because its empty but optional, or because this rule passes”. Note that “If” – it’s not saying the field IS optional, it’s saying it will have to be optional to be OK. The actual optional check is left up to the “required” validation handler.

You can stop now and just remember the two points above. But if you’re keen, let me bend your mind a little further. If you dive into the plugin source code, you see the implementation of optional looks like this:

optional: function( element ) {
			var val = this.elementValue( element );
			return !$.validator.methods.required.call( this, val, element ) && "dependency-mismatch";
		}

Surely the first part of line 3 is testing whether the field is required? Actually, no it’s not. It’s just calling the same function that the real “required” rule would call – in other words (leaving aside complications with dependencies), testing whether the field is empty.

Summary: in this code, “optional” means “empty”, “required” may mean “empty” or “required” depending on the context, and “dependency-mismatch” means “true”. In the immortal words of Phil Karlton