newbie
newbie

Reputation: 14950

How to validate if studentNo is a 11-digit no

Good day!

I have a class Student with attribute String studentNo

Using OO, how can I validate if the input is an 11-digit no.

I can do this:

If(studentNo.length()<11){

}

to validate.. but how can I determine if it is a number or not.

And what are the other methods on how can I do this validation.

Any help would be highly appreciated. Thank you.

Upvotes: 0

Views: 793

Answers (5)

Piotr Wilkin
Piotr Wilkin

Reputation: 3501

Semantically, you could use

try {
    new BigInteger(studentNo);
} catch (NumberFormatException e) {
    ...
}

However, the regexp solutions might be more elegant with respect to the "don't use exceptions as a form of input checking" paradigm (exception handling is generally more expensive than simple checks). So, it depends on whether you want the code to be semantically clear or whether you want it to be efficient.

Upvotes: 0

You can check the following:

  • The length of the string is 11.
  • Each of the 11 character is a zero, a one, a two, a three, a four, a five, a six, a seven, an eight or a nine.

For a complex check you frequently store the result in a boolean. First setting it to true and if any of the conditions fail you set it to false. You then know in the end if all conditions held, by seing that it is still true.

Upvotes: 3

sarahTheButterFly
sarahTheButterFly

Reputation: 1952

Use regex:

http://en.wikipedia.org/wiki/Regular_expression

For example, in java you would do this:

studentNo.matches("[0-9]{11}");

Upvotes: 0

Chris Eberle
Chris Eberle

Reputation: 48795

You would want to use a regular expression, like this:

^[0-9]{11}$

Upvotes: 5

Aaron Gage
Aaron Gage

Reputation: 2403

bool isNum = true;
try {
    Integer.parseInt(studentNo);
}
catch (NumberFormatException e {
    // if we hit here it is not a number...
    isNum = false;
}

Upvotes: 2

Related Questions