Wednesday, August 3, 2011

Disable client-side HTML5 form validation while developing

HTML5 provides new features that will make the job simplier for web developers, and also for users. Among them, the client-side validation with required attribute.


Symfony2 framework enables the generation of this attribute in its forms. But when i'm developping, i don't want this client-side validation cause it's locking the process before the server-side validation. I want my site to be compatible with HTML4 and HTML5 so i can't rely on this client-side validation (anyway i never rely on client-side treatments) and i don't want to use a HTML4 browser for development. So I looked for an option in FF5 to disable this browser HTML5 feature, but i never found it...

So, I used JavaScript and jQuery and wrote this piece of code :

window.onload = function ()
{
  $("[required]").each(function()
    {
      $(this).removeAttr('required');
    }
  );
}

Then winzou suggested a better solution with less form tags than input to treat :

window.onload = function ()
{
  $('form').each(function()
    {
      $(this).attr('novalidate', 'novalidate');;
    }
  );
}

And i include this script in my Twig layout, only in dev environment :

{% if app.environment == 'dev' %}
<script src="{{ asset('bundles/mybundle/js/dev.js') }}" type="text/javascript"></script>
{% endif %}

2 comments :

winzou said...

You can as well add a novalidate attribute to your forms, like $('form').attr('novalidate', 'novalidate').

Nice tip, thanks for the idea!

PéCé said...

This is obviously more efficient ! Thanks!

Post a Comment

Comments are moderated before being published.