I have the Custom field Credit Card on my Account object. When User Submit Credit Card information I want to format & mask it like below

For ex: If Credit Card Value is 1234 8907 2345 8101, before saving I wan to format and masks both. So it should like below


How I can do this? What approach do I need to take. Will it be possible using the salesforce OOB features?

I have created Credit Card field as a Number (16,0). Do I need to create it as text ?


You should define Credit Card Number as text (encrypted) field as follows:

enter image description here

For validating format of credit card, use validation rule with REGEX as follows:

NOT( REGEX( Credit_Card_Number__c , "(((\\d{4}-){3}\\d{4})|\\d{16})?"))

Validates that a custom text field called Credit_Card_Number is formatted in 9999-9999-9999-9999 or 9999999999999999 number format when it is not blank. The pattern specifies:

  • Four digits (0-9) followed by a dash: \d{4}-
  • The aforementioned pattern is repeated three times by wrapping it in () {3}
  • Four digits (0-9)
  • The OR character (|) allows an alternative pattern of 16 digits of zero through nine with no dashes: \d{16}

Refer : Miscellaneous Sample Validation Rules

  • How we can apply validation here? If I enter 8 digits only, still it accepts and saves the values, but format like (XXXX-XXXX-XXXX-7890) which is wrong. It should show error only. What you say ? – user4567570 May 21 '17 at 18:08
  • check my answer, including validation rule – Santanu Boral May 21 '17 at 18:13

This should be done using an encrypted text field. Credit card is a native option.


In order to transform a field before saving, you have to use a Visualforce page or otherwise pass the data through an Apex class before the insert call to the database. Your field will need to be a text field, and the code looks something like:

public void assignToMasked(Account accn, string creditCard)
    accn.Credit_Card_Number__c = 'XXXX-XXXX-XXX-' + creditCard.right(4);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.