Press ESC to close

Cancelling out of HTML5 browser validations !

This post is based on a short scary movie, I was working on a cool HTML-5 page

 <apex:page .... docType="html-5.0"/>

But all the coolness disappeared when powers of 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" />

On hitting the cancel button like this, HTML5 and browser acted smart and ruined all the fun, i.e. got 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 get out of this situation.

On further searching over stackexchange etc, found that developers ran into this issue before. One of popular suggested solution suggested is following

<apex:form html-novalidate="novalidate">

Sadly, this approach disabled all other nice HTML form validations, like minimum number

<input type="number" min="100"/>

Which again block user from entering values below 100. 

Better Solution ? 

Solution which lets user cleanly exit form, via any thing with visualforce action attribute immediate=’true’, i.e.

  • Hitting Cancel button on any visualforce page.

  • Hitting any other button with immediate=’true’, like 

    • Discard Changes

    • A UI where user can save incomplete form via “Save as Draft” button.

    • Clone button for bunch of Grid rows, where its not necessary to comply with validations before cloning.

    • Add Row or Delete Row buttons

    • etc etc

So better solution is certainly something which lets us bypass validations on such specific buttons. Luckily doing that is pretty simple, just add “formnovalidate” attribute as indicated below:

<apex:commandButton action="{!cancel}" value="Cancel" immediate="true" 
                    html-formnovalidate="formnovalidate" />

This will only bypass validations on cancel button press.

Here is a fully working and portable code snippet which you can quickly try in your DE org.

<apex:page standardController="Contact" docType="html-5.0">

    <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:inputField value="{!Contact.FirstName}" required="true" ></apex:inputField>

Hope this could save your time on a dark day with force 🙂 

Leave a Reply

%d bloggers like this: