function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
N cN c 

how to write a validation rule when Year and Month filed is same

i have a  object and fields are Year__c and Month__c, when user is trying to insert another record with the same year and same month. we need to throw an error
Allan MunroAllan Munro
This my opinion but a Validation Rule may not be the right solution for your problem.  I would likely create an Apex Before trigger that queries existing records for any that match on month and year.

Below code is just sample and may not compile.

Trigger MyObjecttInsert on MyObject(before insert)
{
  for(MyObject a : Trigger.new)
  {
     List<MyObject > mynew = [select id, name from MyObject where year__c = :a.year__c and month__c = a.month__c];
     if(mynew.size()>0)
     {
        a.name.addError('MyObject with Month Year existing');
     }
  }
}
RD@SFRD@SF
Hi NC,

You can do this using configuration also, mark the field as unique. Whenever a new record with a same year and month is created an error would be thrown.

Hope it helps
RD
Allan MunroAllan Munro
RD@SF Do you know if  there a way to configure uniqueness across multiple fields?  You idea would work well if the month and year are contained in a single field.
RD@SFRD@SF
Create a new field which is update on creation which is set as unique, you will get an error message when duplicate is created. You don't have to keep it on the page layout Get Outlook for Android