Find your content:

Search form

You are here

How to check a string has only numbers?

 
Share

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

Postal code can have alphanumeric.


Attribution to: Keepcalmncode

Possible Suggestion/Solution #1

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


Attribution to: Arun

Possible Suggestion/Solution #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();
}

Attribution to: Rune Waage

Possible Suggestion/Solution #3

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

Attribution to: BritishBoyinDC

Possible Suggestion/Solution #4

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
}

Attribution to: Jon Hazan
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/1886

My Block Status

My Block Content