11

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

Postal code can have alphanumeric.

1
  • 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, 2013 at 18:08

4 Answers 4

2

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);
}
21

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);

if(postalMatch.Matches()){
    //has only numbers
}
9
  • 6
    The '\d' character class is also available as a shorthand option.
    – Mike Chale
    Oct 3, 2012 at 11:37
  • 2
    Long answer: check out regular-expressions.info/tutorial.html.
    – Mike Chale
    Oct 3, 2012 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, 2012 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, 2013 at 17:01
  • 3
    @KevinP Actually, ^\\d{5}(-\\d{4})?$ would be the correct format in Apex Code.
    – sfdcfox
    Sep 23, 2013 at 18:09
16

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

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_string.htm

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

isNumeric()

Example:

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

2

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();
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .