[SalesForce] how to show the validation error below the input field in VF page

I have used the following code for the email validation and the validation is working fine but I would like to show the error like the the image. how to do that?

My Code:

 <apex:pageBlock id="myblock">
       Email  <apex:inputText value="{!email}" id="email"/><br/><br/>
        <apex:commandButton value="Click me!"  action="{!checkEmail}"/>
 </apex:pageBlock>

Apex:

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

My expected View:

enter image description here

Best Answer

Try below code:

<apex:pageBlock id="myblock">
    Email <apex:inputText value="{!email}" id="email"/><br/><br/>
    <div class="errorMsg">
        <strong></strong>&nbsp;{!emailError}
    </div>
    <apex:commandButton value="Click me!"  action="{!checkEmail}"/>
</apex:pageBlock>

Apex:

if(!Pattern.matches('[a-zA-Z0-9._-]+@[a-zA-Z]+.[a-zA-Z]{2,4}', email))
        {
         emailError ='Either first name or middle name must be defined';
        }
Related Topic