As simple as possible, as complex as necessary

Simple disabling of HTML5 form validation to test server-side checks

10 August 2012

Update 11 March 2012: Please ignore this post. There is a much simpler solution.

For a long time my general approach to form validation has been "server-side is sufficient". Why bother writing and maintaining javascript when you have to have the server-side rules anyway (in case JS is absent on the client)?

In fact there's a very good reason: fewer requests to the server, which means a more responsive UI and less network traffic and server-side processing. But on balance I've felt the complexity of maintaining two sets of code doing the same thing isn't justified in most cases.

With HTML5, however, basic client-side validation now comes free with the new input semantics which, as I wrote last year, I've been happily using in my forms.

The only snag is that, unless you go to the trouble of using an old browser that doesn't recognise it, the HTML5 validation naturally prevents you from submitting empty or invalid values to test out the server-side rules (just disabling Javascript won't disable the validation).

This bit of jQuery solves that problem by disabling any required attributes and reverting the new input types to "text" so that urls and email addresses won't be validated in the browser.


$( "input" ).each
		var $input	=	$( this ).attr( "required",false );
		// certain input types shouldn't be changed
		var typesToIgnore	=	/(button|checkbox|file|hidden|image|radio|submit)/i;
		var inputType	= $input.attr( "type" );
		if( typesToIgnore ) > -1 )
			return true;// skip to the next iteration
		// change the input type by temporarily detaching it from the DOM
		$temporaryMarker	=	$( "<b />" ).insertBefore( $input );
			.attr( "type","text" )
			.insertAfter( $temporaryMarker );

Note that changing an input's type via script is not universally allowed amongst browsers (IE has prevented this for some time, but Firefox does so too nowadays it seems), so I have used a clever workaround to be found on StackOverflow of detaching, modifying and re-attaching the input.

So when creating any form with validation, I now add a commented script include to the above file and uncomment it when I'm ready to test the server-side rules.


  • Formatting comments: See this list of formatting tags you can use in your comments.
  • Want to paste code? Enclose within <pre><code> tags for syntax higlighting and better formatting and if possible use script. If your code includes "self-closing" tags, such as <cfargument>, you must add an explicit closing tag, otherwise it is likely to be mangled by the Disqus parser.
Back to the top