Menu

As simple as possible, as complex as necessary

(Much) Simpler disabling of HTML5 form validation to test server-side checks

11 March 2013

A few months ago I posted what I thought was a cunning little jQuery function to suspend a form's client-side HTML5 validation attributes to allow server side checks to be tested.

disableHtml5FormValidation.js

$( "input" ).each
(
	function()
	{
		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( inputType.search( typesToIgnore ) > -1 )
			return true;// skip to the next iteration
		// change the input type by temporarily detaching it from the DOM
		$temporaryMarker	=	$( "<b />" ).insertBefore( $input );
		$input
			.detach()
			.attr( "type","text" )
			.insertAfter( $temporaryMarker );
		$temporaryMarker.remove();
	}
);

It runs through the form inputs, removes any required attributes and changes their HTML5 types (e.g. "email") back to normal "text" so that the browser checks are disabled.

Since then I've been adding the file as a commented include on each of my forms, and uncommenting it when I need to test the server-side validation.

I'd been meaning to extend it to cover required select elements, but a routine visit to the HTML5 Doctors' surgery earlier today made me realise that my code is seriously overweight as it is, and needs to go on a diet.

It seems the entire function can be slimmed down to this one liner:

$( "form" ).attr( "novalidate",true );

In fact, what's the point in having a function at all? In less than the time it takes to include and comment/uncomment it, I can simply add/remove the attribute to the form itself:

<form action="process" method="post" novalidate>

Learning is often the path to simplicity.

Comments

  • 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