I need to check if the Lead Postal code has only numbers in my Apex code.

Postal code can have alphanumeric.

  • 2
    Postal Codes are often alphanumeric outside the US. You should probably make sure which country is addressed before blindly assuming that the postal code must one particular format.
    – sfdcfox
    Sep 23 '13 at 18:08

Unless you are enforcing it somewhere else, US Zip codes can be alpha-numeric if someone enters a 9 digit zip - so I tend to use this pattern to cover both:

public static Boolean CheckValidZip(String sZip) {
return Pattern.matches('\\d{5}(-\\d{4})?',sZip);

You can use a regular expression ^[0-9]+$ with a pattern matcher to check this.

Update As pointed out by Mike Chale in the comments you can also use: ^\d+$

Untested Example:

Pattern isnumbers = Pattern.Compile('^[0-9]+$');
Matcher postalMatch = isnumbers.matcher(PostalCode);

    //has only numbers
  • 6
    The '\d' character class is also available as a shorthand option.
    – Mike Chale
    Oct 3 '12 at 11:37
  • 2
    Long answer: check out regular-expressions.info/tutorial.html.
    – Mike Chale
    Oct 3 '12 at 12:49
  • 3
    Short answer: the ^ represents the beginning of the line, $ is the end. The + represents 1 or more matches and * is any number of matches.
    – Mike Chale
    Oct 3 '12 at 12:50
  • 2
    Regex will work, and are, I think, the only way to go prior to API 26? But now we have isNumeric, as Arun pointed out. I'm hesitant to invoke a regex unless I absolutely have to. Regex's aren't always the speediest thing in the world.
    – Kevin P
    Sep 23 '13 at 17:01
  • 3
    @KevinP Actually, ^\\d{5}(-\\d{4})?$ would be the correct format in Apex Code.
    – sfdcfox
    Sep 23 '13 at 18:09

Apex comes with range of methods within String class, below i provided the link


We doesn't need to use the Pattern class here. There is instance method in apex String class



String numeric = '123';
system.debug('Is Numeric :: '+numeric.isNumeric()); //returns true

String alphanumeric = '123abc';
system.debug('Is Numeric :: '+alphanumeric.isNumeric()); //returns false

Kindly let me know in case of any clarification


Here is a method that returns true if the input is a positive or negative number.

public Boolean isNumber(String str) {
     Pattern isnumbers = Pattern.Compile('^[-]?[0-9]+$');
     Matcher numberMatch = isnumbers.matcher(str);
     return numberMatch.Matches();

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.