+ Start a Discussion
Force.platformForce.platform 

validate text field

Hello, 
I have visualforce page, that recive input value from user. page have twi fields inputText(name),inputText(name) and InputTextArea(Address),
i want to add validation that, when user click on save button, these three fields should not empty.
public class EComm_Bucket_Controller 
{public String n{get; set;}
public String a{get; set;}
public Integer q{get; set;}

public pageReference placeOrderForSinglePro()
  {
    Id Prodname=ApexPages.currentPage().getParameters().get('Pname');
    Decimal Proprice = Decimal.valueOf(ApexPages.currentPage().getParameters().get('price'));
   if(!(n!=null))
   {
   
    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'Please enter value'));
   }else
   {
    EOrder__c ord=new EOrder__c(EP_del__c=Prodname,
                                OQuantity__c=q,
                                Contact_Name__c=n,
                                Delivery_Address__c=a,
                                Order_Status__c='Placed',
                                Total_Order_Ammount__c=q*Proprice );
    insert ord;
    }
}

I have added <apex:pageMessage> on vf. but its not working. i have to check for 3 fields. Oquantity is number field. 
RKSalesforceRKSalesforce
Hi Arati,

Please try adding required attribute to your field:
<apex:inputfield required="true" value="" />

 
Waqar Hussain SFWaqar Hussain SF
Hi Arati, 

use below code snippet
 
public class EComm_Bucket_Controller 
{
public String n{get; set;}
public String a{get; set;}
public Integer q{get; set;}

public pageReference placeOrderForSinglePro()
  {
    Id Prodname=ApexPages.currentPage().getParameters().get('Pname');
    Decimal Proprice = Decimal.valueOf(ApexPages.currentPage().getParameters().get('price'));
   if(n == null || q == null || n == null)
   {
   ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Please enter values in all fields.');
	ApexPages.addMessage(myMsg);
	return null;
   }else
   {
    EOrder__c ord=new EOrder__c(EP_del__c=Prodname,
                                OQuantity__c=q,
                                Contact_Name__c=n,
                                Delivery_Address__c=a,
                                Order_Status__c='Placed',
                                Total_Order_Ammount__c=q*Proprice );
    insert ord;
	ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.Info,'Record Created successfully.');
	ApexPages.addMessage(myMsg);
	return null;
    }
	return null;
}

 
Suraj TripathiSuraj Tripathi
Hi Arati,
Below is the code for the same. It is working fine in my Org.


VF Page Code :
<apex:page controller="AddErrorCtrl" tabStyle="Account">
    <style>
    .error{ border:1px solid red !important;}
    .messageClass{color: red; display: inline; float: right;position: absolute;margin: 3px;font-size:11px}
    </style>
    <apex:messages />
    <apex:form >
        <apex:pageBlock title="Hello {!$User.FirstName}!" id="pblock">
       
        <p> 
            Number of Employees: <apex:inputText value="{!account.NumberOfEmployees}" id="Employee_validation"/>
        </p>
        <p>
            <input type="button" value=" Save " onclick="validateFields();" class="btn"/>
            <apex:actionFunction action="{!save}" name="SaveAF" rerender="pblock" />
        </p>
        </apex:pageBlock>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.js" ></script>
        <script>
            var isValidate = true;
            function validateFields()
            {
                var varFieldlist = [ "Employee_validation"];
                validateRequiredFields(varFieldlist);
                if(isValidate)
                {
                    SaveAF();
                }
            }
            function validateRequiredFields(arrayFields){
                $.each( arrayFields, function( i, val ) {
                    if($('[id$='+val+']').val() =='')
                    {
                        if(!$('[id$='+val+']').hasClass('error'))
                        {
                            $('[id$='+val+']').addClass('error');
                            $('[id$='+val+']').after("<p class='messageClass' id="+'__'+val+"> Required </p>");
                            isValidate = false;
                        }
                    }
                    else if($('[id$='+val+']').hasClass('error'))
                    {
                        $('[id$='+val+']').removeClass('error');
                        $('[id$=__'+val+']' ).remove();
                        isValidate = true;
                    }
                });
            }
        </script>
    </apex:form>
</apex:page>

Controller Code :
public class AddErrorCtrl {
    Account account;

    public PageReference save() {
        if(account.NumberOfEmployees == null)
        {
            account.NumberOfEmployees.addError('You must enter a value.');
            return null;
        }
        try{
            update account;
        }
        catch(DmlException ex){
            ApexPages.addMessages(ex);
        }
        return null;
    }

    public String getName() {
        return 'MyController';
    }

    public Account getAccount() {
        if(account == null)
        account = [select id, name, numberofemployees from Account
        where id = :ApexPages.currentPage().getParameters().get('id')];
        return account;

    }
}

Screenshot:

User-added image

Hope it Helps you. Please mark this as solved so that it gets removed from the unanswered queue which results in helping others who are encountering a similar issue.

Regards ,
Suraj
Force.platformForce.platform

Hello Waqar Hussain,

your solution is working for only quantity field. its not showing message for inputText and inpitTextArea field
Waqar Hussain SFWaqar Hussain SF
Can you share you code?
Force.platformForce.platform
Hello Hussain,
This is my Vf:
<apex:page controller="EComm_Bucket_Controller" action="{!itemInMyBucket}" >
<style>
        .myFormStyle {
            background-color: Moccasin ;
            border:2px solid Violet;
        }
    </style>
    
    <style>
  /*for page block */     
.bPageBlock{
        width : 100%;
        }
        </style>
        
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $(".bPageBlock").css("background-color","Aquamarine");
        $(".bPageBlock").css("border-color","Aquamarine");
    });
    </script>
    
<apex:form styleClass="myFormStyle " >
<center>
  <apex:pageBlock title="My Bucket" >
  <apex:pageMessages id="msg"> </apex:pageMessages>
  
  <apex:pageblockSection >
  <apex:pageBlockTable value="{!itemInBucket}" var="i">
  
    <!--<apex:column value="{!i.name}"/>-->
    <apex:column value="{!i.Product_Name__c}"/>
    <apex:column value="{!i.price__c}"/>
    
    <apex:column headerValue="Quantity" >
    <apex:inputText value="{!q}" />
    </apex:column>
    
    <!--<apex:column headerValue="Name" >
    <apex:inputText value="{!n}" />
    </apex:column>
    
    <apex:column headerValue="Address" >
    <apex:inputText value="{!a}" />
    </apex:column>-->
    
    <apex:Column >
    <apex:commandLink value="Place Order" action="{!placeOrderForSinglePro}">
    <apex:param name="Pname" value="{!i.Product_Name__c}"/>
    <apex:param name="price" value="{!i.price__c}" />
    </apex:commandLink>
    </apex:column>
    
    <apex:Column >
    <apex:commandLink value="cancel" action="{!cancelOrder}" rendered="true">
    
    
    </apex:commandLink>
    </apex:column>
    
    </apex:pageBlockTable> 
    </apex:pageblockSection>
    
    <apex:pageBlockSection >
    <apex:inputText value="{!n}" label="Name" />
    <apex:inputTextarea title="Address" value="{!a}"/>
   </apex:pageBlockSection>
  </apex:pageBlock>
  </center>
  <apex:commandLink value="View Order" action="{!openOrderPage}"/>
  <apex:commandLink value="Previous Page" style="float:right;" action="{!redirect}"/>
  </apex:form>
</apex:page>

Controller:
public class EComm_Bucket_Controller 
{  
Public List<EOrder_Item__c> itemInBucket{get; set;}
public List<EOrder_Item__c> itemToDelete{get; set;}
public Integer q{get; set;}
public String n{get; set;}
public String a{get; set;}

  public pageReference itemInMyBucket()
  {
     itemInBucket=[select id,
                   name,
                   Quantity__C,
                   Product_Name__c,
                   Price__C 
                   from EOrder_Item__c 
                   WHERE Name!=NULL AND Flag__c=TRUE];
     System.debug('list=='+itemInBucket);
     return null;
  }
  
//------------------Place Order Button-for single record-------------------------
  public pageReference placeOrderForSinglePro()
  {
    Id Prodname=ApexPages.currentPage().getParameters().get('Pname');
    Decimal Proprice = Decimal.valueOf(ApexPages.currentPage().getParameters().get('price'));
   if(q==0 || n==null || a==null)
   {
   ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Please enter value in all fields');
    ApexPages.addMessage(myMsg);
    }
    //return null;
   /*system.debug('********'+q);
    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'Please enter value'));*/
   else
   {
    EOrder__c ord=new EOrder__c(EP_del__c=Prodname,
                                OQuantity__c=q,
                                Contact_Name__c=n,
                                Delivery_Address__c=a,
                                Order_Status__c='Placed',
                                Total_Order_Ammount__c=q*Proprice );
    insert ord;
    apexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.Info,'Order Created successfully.');
    ApexPages.addMessage(myMsg);
    return null;
    }
    
              //------------------show only one item on bucket page----------
    List<EOrder_Item__c> processeditemInBucket = [select id,
                                                  name, 
                                                  Quantity__C,
                                                  Product_Name__c 
                                                  from EOrder_Item__c 
                                                  WHERE Name!=NULL AND Flag__c=TRUE];
    for(EOrder_Item__c v:processeditemInBucket)
        {
            v.Flag__c =FALSE;
            
        }
      update  processeditemInBucket;
    return null;
  }
  
//-------------to cancel Oredr--------------------  
  public pageReference cancelOrder()
  {
     itemToDelete=[select id,
                   name,
                   Quantity__C,
                   Product_Name__c 
                   from EOrder_Item__c 
                   WHERE Name!=NULL AND Flag__c=TRUE];
     delete itemToDelete;
     System.debug('list=='+itemInBucket);
     return null;
  }
  
//----------------------Place order for All-for multiple record-----------------------
  public PageReference placeOrderForAllPro()
  {
   return null;
  }

 
public PageReference redirect()
    {
   PageReference pr = new PageReference('/apex/EComm_Landing_Page');
   return pr;
   }
   
   
   
public PageReference openOrderPage()
    {
   PageReference pr = new PageReference('/apex/Final_Order_Page');
   return pr;
   }
}
Waqar Hussain SFWaqar Hussain SF
<apex:page controller="EComm_Bucket_Controller" action="{!itemInMyBucket}" >
<style>
        .myFormStyle {
            background-color: Moccasin ;
            border:2px solid Violet;
        }
    </style>
    
    <style>
  /*for page block */     
.bPageBlock{
        width : 100%;
        }
        </style>
        
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $(".bPageBlock").css("background-color","Aquamarine");
        $(".bPageBlock").css("border-color","Aquamarine");
    });
    </script>
    
<apex:form styleClass="myFormStyle " >
<center>
  <apex:pageBlock title="My Bucket" >
  <apex:pageMessages id="msg"> </apex:pageMessages>
  
  <apex:pageblockSection >
  <apex:pageBlockTable value="{!itemInBucket}" var="i">
  
    <!--<apex:column value="{!i.name}"/>-->
    <apex:column value="{!i.Product_Name__c}"/>
    <apex:column value="{!i.price__c}"/>
    
    <apex:column headerValue="Quantity" >
    <apex:inputText value="{!q}" required="true"/>
    </apex:column>
    
    <!--<apex:column headerValue="Name" >
    <apex:inputText value="{!n}" required="true"/>
    </apex:column>
    
    <apex:column headerValue="Address" >
    <apex:inputText value="{!a}" required="true"/>
    </apex:column>-->
    
    <apex:Column >
    <apex:commandLink value="Place Order" action="{!placeOrderForSinglePro}">
    <apex:param name="Pname" value="{!i.Product_Name__c}"/>
    <apex:param name="price" value="{!i.price__c}" />
    </apex:commandLink>
    </apex:column>
    
    <apex:Column >
    <apex:commandLink value="cancel" action="{!cancelOrder}" rendered="true">
    
    
    </apex:commandLink>
    </apex:column>
    
    </apex:pageBlockTable> 
    </apex:pageblockSection>
    
    <apex:pageBlockSection >
    <apex:inputText value="{!n}" label="Name" />
    <apex:inputTextarea title="Address" value="{!a}" required="true"/>
   </apex:pageBlockSection>
  </apex:pageBlock>
  </center>
  <apex:commandLink value="View Order" action="{!openOrderPage}"/>
  <apex:commandLink value="Previous Page" style="float:right;" action="{!redirect}"/>
  </apex:form>
</apex:page>

public class EComm_Bucket_Controller 
{  
Public List<EOrder_Item__c> itemInBucket{get; set;}
public List<EOrder_Item__c> itemToDelete{get; set;}
public Integer q{get; set;}
public String n{get; set;}
public String a{get; set;}

  public pageReference itemInMyBucket()
  {
     itemInBucket=[select id,
                   name,
                   Quantity__C,
                   Product_Name__c,
                   Price__C 
                   from EOrder_Item__c 
                   WHERE Name!=NULL AND Flag__c=TRUE];
     System.debug('list=='+itemInBucket);
     return null;
  }
  
//------------------Place Order Button-for single record-------------------------
  public pageReference placeOrderForSinglePro()
  {
    Id Prodname=ApexPages.currentPage().getParameters().get('Pname');
    Decimal Proprice = Decimal.valueOf(ApexPages.currentPage().getParameters().get('price'));
   if(q == null || n==null || a==null)
   {
   ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Please enter value in all fields');
    ApexPages.addMessage(myMsg);
    }
   else
   {
    EOrder__c ord=new EOrder__c(EP_del__c=Prodname,
                                OQuantity__c=q,
                                Contact_Name__c=n,
                                Delivery_Address__c=a,
                                Order_Status__c='Placed',
                                Total_Order_Ammount__c=q*Proprice );
    insert ord;
    
              //------------------show only one item on bucket page----------
    List<EOrder_Item__c> processeditemInBucket = [select id,
                                                  name, 
                                                  Quantity__C,
                                                  Product_Name__c 
                                                  from EOrder_Item__c 
                                                  WHERE Name!=NULL AND Flag__c=TRUE];
    for(EOrder_Item__c v:processeditemInBucket)
        {
            v.Flag__c =FALSE;
            
        }
      update  processeditemInBucket;
    apexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.Info,'Order Created successfully.');
    ApexPages.addMessage(myMsg);
    return null;
	}
	return null;
  }
  
//-------------to cancel Oredr--------------------  
  public pageReference cancelOrder()
  {
     itemToDelete=[select id,
                   name,
                   Quantity__C,
                   Product_Name__c 
                   from EOrder_Item__c 
                   WHERE Name!=NULL AND Flag__c=TRUE];
     delete itemToDelete;
     System.debug('list=='+itemInBucket);
     return null;
  }
  
//----------------------Place order for All-for multiple record-----------------------
  public PageReference placeOrderForAllPro()
  {
   return null;
  }

 
public PageReference redirect()
    {
   PageReference pr = new PageReference('/apex/EComm_Landing_Page');
   return pr;
   }
   
   
   
public PageReference openOrderPage()
    {
   PageReference pr = new PageReference('/apex/Final_Order_Page');
   return pr;
   }
}

use above code snippets.