+ Start a Discussion
Gallery IntegrationGallery Integration 

Controller Class to Validate duplicate email address in Visualforce page

Hi Everyone,

I have created a simple visualforce page to create a new contact.
However, I want to make a validation to pop out an error message if the email is already existed.

What can I add in the controller class to achieve this?

Here is the code for the visualforce page
<apex:page standardController="Contact">

    <h1>Registration Page</h1>

    <apex:form >

        <apex:pageMessages />



                <th>First Name:</th>

                <td><apex:inputText value="{Contact.FirstName}"/></td>


                <th>Last Name:</th>

                <td><apex:inputText value="{!Contact.LastName}"/></td>



                <th>Email Address:</th>

                <td><apex:inputText value="{!Contact.Email}"/></td>

            <apex:pageBlockButtons location="bottom">
     		<apex:commandButton action="{!save}" value="Save"/>




Really appreciate for the help

NagendraNagendra (Salesforce Developers) 
Hi Gallery,

You can do this by writing a simple trigger.

UseCase: The companies' website has a PHP insert, creating Contacts in Salesforce. However, it is possible that the contact already exists in Salesforce. (The current PHP module does not allow for external ids). My solution is to throw a specific error if the Contact email already exists.

Sample Code:
trigger trig_Contact_webToContact on Contact (before insert) 
  final String errMsg = 'The email already exists on another Contact: ';
  Set< String > emailSet = new Set< String >();
  for( Contact c : Trigger.new ) emailSet.add( c.Email );

  Map< String, Id > duplicateContactMap = new Map< String, Id >();

  for( Contact c : [select Id, Email from Contact where Email = :emailSet] )
    duplicateContactMap.put( c.Email, c.Id );

  for( Contact c : Trigger.new ){
    Id duplicateContactId = duplicateContactMap.get( c.Email );
    if( duplicateContactId != null )
      c.addError( errMsg + duplicateContactId );
Hope this helps.

Kindly mark this as solved if the reply was helpful.

Gallery IntegrationGallery Integration
Hi Nagrenda,

Thanks for your assistance.
Do you have a sample of code on how to use this php insert method?
Is it better to use this method rather than using visualforce page?

Also, If we want to update an information to the contact object, could we use this php method?

Thanks and Regards,