简体   繁体   中英

user input validation java classes

This is my validation for user ID number, when testing, I entered an invalid string with a length less than 10 and it sets the input and doesn't execute the else statement.

The Source Code:

private String phoneNum;

public personalInfo(String phNum) {
    setPhoneNum(phNum);
}

public String getPhoneNum() {
    return phoneNum;
}

public void setPhoneNum(String phNum) {
    if (phoneNum.startsWith("05")&&(phoneNum.length()==10)){
        phoneNum = phNum;
    }
    else throw new IllegalArgumentException ("Invalid Phone Number!");
}

your method looks like this...

public void setPhoneNum(String phNum) {
    if (phoneNum.startsWith("05")&&(phoneNum.length()==10)){
        phoneNum = phNum;
    }

and there you are not validating the parameter, but the variable phoneNum ...

do instead:

public void setPhoneNum(String phNum) {
    if (phNum.startsWith("05")&&(phNum.length()==10)){
        phoneNum = phNum;
    }

You should be validating the value you that you are getting ( phNum ) and set it to the member variable phoneNum .

if (phNum.startsWith("05")&&(phNum.length()==10)){
    phoneNum = phNum;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM