开发者

Prevent Negative numbers for Age without using client side validation

I have an issue in Core java. Consider the Employee class having an attribute called age.

class Employee{           
      private int age;     
      public void setAge(int age);   开发者_如何学C  
}

My question is how do i restrict/prevent setAge(int age) method such that it accepts only positive numbers and it should not allow negative numbers,

Note: This has to be done without using client side validation.how do i achieve it using Java/server side Validation only.The validation for age attribute should be handled such that no exception is thrown


You simply have to validate the input from the user in the method:

public void setAge(int age) {
    if (age < 0) 
        throw new IllegalArgumentException("Age cannot be negative.");
    // setter logic
}

If you cannot throw an exception then you might wanna try:

public boolean setAge(int ageP) {
    // if our age param is negative, set age to 0
    if (ageP < 0) 
        this.age = 0
    else 
        this.age = ageP;
    // return true if value was good (greater than 1) 
    // and false if the value was bad
    return ageP >= 0;
}

You can return whether or not the value was valid.


Although you say you can't throw an exception, you don't really say what you want to do if the value passed is negative.

You've got to pass the failure in the validation back to the caller some way.

If you want your bean to do this, when you call your setAge method, it's either got to throw an exception or return a value.

So your options are:

public void setAge(int age) {
    if (age < 0) 
        throw new IllegalArgumentException("Age cannot be negative.");
    this.age = age;
}

or

public boolean setAge(int age) {
    if(age < 0) 
        return false;

    this.age = age;
    return true;
}

I guess you don't want to do the second option either since setters don't normally return a value.

If you don't want to do either of these, then put a test in your caller prior to calling the setAge method.


For javabean validation, you should consider using a framework such as JGoodies Validation or Hibernate Validator.

Both are very good frameworks. The Hibernate library is a JSR-303 standard and it is annotation-based. It integrates well with Spring. JGoodies validation integrates very well with JGoodies binding if you also happen to be using your JavaBeans in a Swing GUI.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜