public void setMobile(String mobile) {
      char[] mobileList = mobile.toCharArray();
      boolean isValid = true;
      for(char x : mobileList)
      {
          if(!Character.isDigit(x))
          {
              isValid = false;
          }
      }
      if(isValid)
      {
          this.mobile = mobile;
      }
    }

Is this the best way of doing things? Cheers.

share|improve this question

There is one major flaw that will come back and haunt you with this code. If you enter an invalid number, there is absolutely no indication whatsoever that it was invalid.

If it is not valid, you should do this:

throw new IllegalArgumentException("Invalid mobile number: " + mobile);

Incorporating Heslacher's suggestions I would do this:

public void setMobile(String mobile) {
    if (!containsOnlyDigits(mobile)) {
        throw new IllegalArgumentException("Invalid mobile number: " + mobile);
    }
    this.mobile = mobile;
}
share|improve this answer

You should extract the validation, meaning the checking if the string only contains digits, to a separate method like so

private static boolean containsOnlyDigits(final String value) {
    for (int i = 0; i < value.length(); i++) {
        if(!Character.isDigit(value.charAt(i))) {
            return false;
        }
    }
    return true;
}  

and use it in the setMobile() method like so

public void setMobile(String mobile) {
    if(containsOnlyDigits(mobile)) {
        this.mobile = mobile;
    }
}  

So each method is doing only one thing.

Because the method setMobile() is public you should check if the passed mobile is not null.

Disclaimer: Written in the editor without testing.

share|improve this answer
1  
Java 8: return value.chars().allMatch(i -> Character.isDigit((char) i)); Note that CharacterSequence.chars returns an IntStream – Simon Forsberg 11 hours ago

You can use regex ^\d{1,10}$ to check this as below example:

private static final String regex="^\\d{1,10}$";

public static void main(String[] args) {
    System.out.println("123456".matches(regex));
    System.out.println("123abc".matches(regex));
}

Where regex means:

  • ^ -> starts of string
  • \d -> only digits
  • {1, 10} -> min 1 digit, max 10 digits
  • $ -> end of string

So, complete regex -> input string starts with digit, should be minimum 1 digit, max 10 digits, and also ends with digit. And no other characters allowed in between.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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