Prevent negative numbers for Age without using client-side validation

I have a problem in Core java. Consider the Employee class with the age attribute.

class Employee{           
      private int age;     
      public void setAge(int age);     
}

My question is how can I restrict / disable the setAge (int age) method so 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

+3
source share
3 answers

You just need to check the user input 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, you can 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 the value was valid.

+6
source

Although you say that you cannot throw an exception, you really do not say what you want if the passed value is negative.

- .

, bean , setAge, , .

, :

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

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

    this.age = age;
    return true;
}

, , .

- , setAge .

0

javabean , JGoodies Validation Hibernate Validator.

Both are very good frameworks. The Hibernate library is a JSR-303 standard and is based on annotations. It integrates well with Spring. JGoodies validation works very well with JGoodies bindings if you also use JavaBeans in the Swing GUI.

0
source

Source: https://habr.com/ru/post/1790002/


All Articles