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
Vasavi VajinepalliVasavi Vajinepalli 

Number field validation with year and month

Hi,

I've a field called "Year_Month__c" of datatype "Number".
the value for this field should be like 201510 meaning yyyymm. I need to have a validation rule which validates first four digits are valid year or not and last 2 digits should be a valid month. If someone enters, 201078 - it should throw an error as month is not valid.
Can anyone help me in achieving this validation rule for number field.

Thanks in advance.
Vasavi 
Best Answer chosen by Vasavi Vajinepalli
William TranWilliam Tran
There are many ways to do this, the cleanest is probably a validation rule using REGEX like this:

NOT(
  REGEX(Text(Year_Month__c), "[0-9]{4}(0[1-9]|1[012])")
)

As a common practice, if your question is answered, please choose 1 best answer. 
But you can give every answer a thumb up if that answer is helpful to you. 

Thanks

All Answers

William TranWilliam Tran
There are many ways to do this, the cleanest is probably a validation rule using REGEX like this:

NOT(
  REGEX(Text(Year_Month__c), "[0-9]{4}(0[1-9]|1[012])")
)

As a common practice, if your question is answered, please choose 1 best answer. 
But you can give every answer a thumb up if that answer is helpful to you. 

Thanks
This was selected as the best answer
Vasavi VajinepalliVasavi Vajinepalli
Thanks for the quick response William. Can you please clarify me that this RegEx works for Number field or it can work for Date field as well. Also i just want to tell you that my field will not contain day means it will have only yyyymm. Can you please explain how this RegEx works.

Thanks,
Vasavi
William TranWilliam Tran

It assumes that "Year_Month__c" of datatype "Number" as you stated.  Yes it assumes YYYYMM otherwise it will error out.

REGEX just validates that the value has to be a certain format otherwise it will give a validation error.

Thx