Thursday 11 September 2014

Date Validation on Text Field using Pattern, Matcher object in Salesforce


You may have a scenario like you need to type a date value on Text Field and need to validate the date means, you can go for pattern, matcher object.

Here is the code to validate a Date format,

  1. String dateRegEx = '(0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])/((19|20)\\d\\d)';
  2. Pattern myPattern = Pattern.compile(dateRegEx);
  3. Matcher myMatcher = myPattern.matcher('12/01/2012');
  4.  
  5. if(!myMatcher.matches())
  6. {
  7. ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, Please provide the date with the format MM/DD/YYYY'));
  8. }

dateRegEx - It holds the Regular expression to validate date value.

myPattern - Declares the Pattern object and compile the regular expression.

myMatcher  - Matches the given value by initializing matcher object.




No comments:

Post a Comment

Activities: Assign Tasks to a Queue Salesforce Lightning

Salesforce announced to assign Tasks to a Queue beginning from Spring'20 release. How does it work? In Setup, enter Queues in th...