client side validation1

Client-Side Validation

Carrying out validation in the browser when a user submits a form is a technique that has been followed by the number of years. The user is given immediate feedback rather than having to wait for a response from the server, and bandwidth is saved by not submitting the form if there are issues.

In this post, we will create a Visualforce page that allows a user to create a contact record. When the user clicks on Save, client-side validation will take place to ensure that one of the e-mail address or phone number fields has been populated before submitting the form.

This post uses the jQuery (http://jquery.com/) JavaScript framework to swap the buttons. The JavaScript file is included from the Google Hosted Libraries content delivery network.

This post also uses the jQuery Validation plugin to provide validation functionality. This is included in the Microsoft Ajax Content Delivery Network.

<script>// <![CDATA[
$(document).ready(function(){ /* configure the validator - set the email element to required if the phone is empty and vice versa */ var validator = $('[id="{!$Component.createClientform}"]').validate({ debug: true, rules: { '{!$Component.createClientform.pageBlock.pageBlockSection.contactemail}': { required: function() { return $('[id="{!$Component.createClientform.pageBlock.pageBlockSection.contactphone}"]').val()==''; } }, // email '{!$Component.createClientform.pageBlock.pageBlockSection.contactphone}': { required: function() { return $('[id="{!$Component.createClientform.pageBlock.pageBlockSection.contactemail}"]').val()==''; } }, // phone }, // rules messages: { '{!$Component.createClientform.pageBlock.pageBlockSection.contactemail}':"One of Email or Phone must be provided", '{!$Component.createClientform.pageBlock.pageBlockSection.contactphone}':"One of Phone or Email must be provided", } // messages } )});
// ]]></script>

How does it work?

clientside client1

Leaving both the Email and Phone fields blank when saving the record.

When the page is loaded, the jQuery Validation Plugin is activated. Each of the Email and Phone fields is defined as required if the other field is empty:

'{!$Component.createClientform.pageBlock.pageBlockSection.contactemail}': {
    required: function() {
        return $('[id="    {!$Component.createClientform.pageBlock.pageBlockSection.contactphone}"]').val()=='';}
}, // email

Each field has an associated message that is displayed when the field is required but empty. messages:

{
    '{!$Component.createClientform.pageBlock.pageBlockSection.contactemail}':
    "One of Email or Phone must be provided",
    '{!$Component.createClientform.pageBlock.pageBlockSection.contactphone}':
    "One of Phone or Email must be provided",
 } // messages

Page-reference: http://www.slideshare.net/ParisSalesforceDeveloperGroup/salesforce-performance-hacks-client-side

Related Articles

Responses