Cancelling out of HTML5 browser validations!
This post is based on a short, scary movie. I was working on a cool HTML5 page.
<apex:page .... docType="html-5.0"/>
But all the coolness disappeared when the powers of the CANCEL button are gone. The typical Cancel button in Salesforce, which is always tough enough to get out of any validation, i.e.
<apex:commandButton action="{!cancel}" value="Cancel" immediate="true" />
Upon hitting the cancel button like this, HTML5 and the browser acted smart and ruined all the fun, i.e., I got the following error:
Solution?
On some Google search about “How to disable HTML5 form validations”, found a new element attribute named “novalidate” or “formnovalidate” is key to getting out of this situation.
On further searching on Stack Exchange, etc. I found that developers had run into this issue before. One of the popular suggested solutions is the following:
<apex:form html-novalidate="novalidate">
Sadly, this approach disabled all other nice HTML form validations, like the minimum number.
<input type="number" min="100"/>
Better Solution?
Solution which lets user cleanly exit form, via anything with visualforce action attribute immediate=’true’, i.e.
Hitting the Cancel button on any Visualforce page.
Hitting any other button with immediate=’true’, like
Discard Changes.
A UI where the user can save an incomplete form via the “Save as Draft” button.
Clone button for a bunch of Grid rows, where it's not necessary to comply with validations before cloning.
Add Row or Delete Row buttons
ETC
So, a better solution is certainly something that lets us bypass validations on such specific buttons. Luckily, doing that is pretty simple, just add the “formnovalidate” attribute as indicated below:
<apex:commandButton action="{!cancel}" value="Cancel" immediate="true" html-formnovalidate="formnovalidate" />
This will only bypass validations on the cancel button press.
Here is a fully working and portable code snippet that you can quickly try in your DE org.
<apex:page standardController="Contact" docType="html-5.0">
<apex:form>
<apex:pageBlock title="Simple Validation Demo">
<apex:pageBlockButtons location="bottom">
<apex:commandButton action="{!cancel}" value="Cancel" immediate="true"
html-formnovalidate="formnovalidate" />
<apex:commandButton action="{!save}" value="Save" />
</apex:pageBlockButtons>
<apex:pageBlockSection>
<apex:inputField value="{!Contact.FirstName}" required="true" ></apex:inputField>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
Hope this could save your time on a dark day with force 🙂