If you are testing your websites and especially your forms with watir-webdriver you might run into trouble because of automatic HTML5 validation in Firefox. Here’s how to fix it by adding some javascript magic.

The problem

When testing a email contact form with watir-webdriver, I encountered a strange error, when I tried submitting some spam values for the email address field with something like the following code:

browser.textfield(id: 'email').set "invalid_email_value"
browser.input(type: 'submit').click

Firefox did not submit the form and I got a error on the console, because the expected error message I was looking for was not present. This is what Firefox displayed:

This is the automatic output by Firefox, after clicking the submit button. The form values are not submitted.

The reason

As HTML5 introduced support for form validation just by specifying certain attributes read more here… Firefox validated the form automatically and avoided the submit. This is cool for users, but for my test it was bad as it did not allow my testing of server-side form validation.

The fix

What we need to do to fix this, is to disable automatic form validation. This can be done by adding the novalidate attribute to your form tag like so:

<form id="form_1" novalidate>

However, you would not want to put that into the source code of your website, as the form validation makes sense for the visitor of your site. So we need to disable form validation through watir-webdriver. We achieve this by adding the following javascript execution to our code (assuming that you use jquery on your site):

browser.execute_script('$( "form" ).each(function( index ) { $( this ).attr("novalidate", "novalidate"); });')
browser.textfield(id: 'email').set "invalid_email_value"
browser.input(type: 'submit').click

It loops through all form tags on your site and adds the novalidate attribute to the tag. After adding this line the form is submitted as expected.