# Make visualforce fields required without setting them from the object page

I have an <apex:form> which has search action and upsert action, the thing is that I want the fields inside this form to be required just when I click on insert button.

I tried to make these fields required from the object page, but then they become required even in search action.

Is there anyway could help me making these fields required just for Add button.

You have to add these fields in <apex:pageBlock> section and then you have to make the field required, it will work!

Example:

<apex:page standardController="MyObject__c"  extensions="MyObjectController" showHeader="true" sidebar="true">
<apex:pageblock mode="edit" title="Search Serials" >
<apex:pageMessages />
<apex:pageblockbuttons >
<!-- add/remove other css classes for button look and feel -->
</apex:pageblockbuttons>
<apex:outputpanel >
<apex:pageblocksection title="Search Serials" showheader="true" columns="2" >
<apex:inputfield id="type" value="{!MyObject__c.Type__c}" required="true" />
<apex:inputfield id="fieldName" value="{!MyObject__c.prifix__c}" required="true"/>
<apex:inputfield id="Start" value="{!MyObject__c.start__c}"/>
<!-- so on... -->
</apex:pageblocksection>
</apex:outputpanel>
</apex:pageblock>
</apex:page>


If you like to make the fields required only for specific actions then either validate on client side by Javascript/JQuery, or server side - custom logic in your action in your controller/extension. The standard visualforce tag parameter required will make the field required at all times when you try to submit the form or call a method in the controller.

I solved it by validating the fields in the APEX controller when I do the upseart operation, So the fields actually aren't required but in the upsert function if there's any field that equals null I display a message.

Otherwise, I didn't use this validation in the search operation so it went will.

public void update_serial(){
if(serial.Type__c != null && serial.Year__c != null && serial.Current__c != null .....){
try{
upsert serial;
serial = new Serial__c();
}catch(Exception e){