Email validation using Apex in Salesforce

Visualforce page:

<apex:page controller="testController">
    <apex:form id="myform">
    <apex:pagemessages />
    <apex:pageBlock id="myblock">
        Email Address: <apex:inputText value="{!email}" id="email"/><br/><br/>
        <apex:commandButton value="Click me!" action="{!checkEmail}"/>
    </apex:pageBlock>
    </apex:form>
</apex:page>


Apex Code:

public class testController
{
    public String email { get; set; }
    public void checkEmail()
    {

        if(!Pattern.matches('[a-zA-Z0-9._-]+@[a-zA-Z]+.[a-zA-Z]{2,4}[.]{0,1}[a-zA-Z]{0,2}', email))
        {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, 'Check your email'));

        }
    }
}


Cheers!!!

4 comments:

  1. What if my email is username@company.co.in or something like that? It does not validate the email.

    ReplyDelete
    Replies
    1. Hi, I have improved the REGEX now. Please let me know if it is not working.

      Delete