简体   繁体   中英

Validate field in form to be an INT in Spring MVC

What is the best practice to do form validation? Specifically when I only have two fields being passed to the back end.

1) Product ID (I need to make sure they are referring to the Product they have access to.) 2) Number of Keys (It must be an INT datatype)

I have a form that submits a product id (from drop down) and the number of keys for that product. I am looking at my code it looks ugly and doesn't seem like a good practice at all. When I call the service it only accepts an INT.

My current code goes as follows.

    if(StringUtils.isEmpty(downloadFormBean.getNbrEcus())){
        logger.debug("User did not enter the number of Keys");
        model.addAttribute("ERROR","Please enter the number of ECU IDs.");
    }else if(!m.containsKey(downloadFormBean.getProduct()) && !m.containsValue(downloadFormBean.getProduct())){
        logger.debug("User attempted to pass a product that was not returned to him. Product:" +downloadFormBean.getProduct());
        model.addAttribute("ERROR","You must submit a product you were provided.");
    }else if(!NumberUtils.isDigits(downloadFormBean.getNbrEcus())){
        logger.debug("User attempted to pass an invalid integer");
        model.addAttribute("ERROR","Please enter a valid integer number!");
    }else if(Long.parseLong(downloadFormBean.getNbrEcus()) > 2147483647){
        logger.debug("User attempted to pass a number larger than 2137483647.");
        model.addAttribute("ERROR","You are attempting to request too many Keys.");
    }else if(Integer.parseInt(downloadFormBean.getNbrEcus()) == 0 ){
        logger.debug("User attempted to submit zero requests.");
        model.addAttribute("ERROR","You must request at least one Key");

Is doing something like this http://www.mkyong.com/spring-mvc/spring-mvc-form-handling-example/ even worth the trouble and will it cover checking for an INT.

Any criticism is highly valued

In your method that deals with form value binding/form submission, the value of the numeric field should be set as a parameter with the @PathVariable annotation and this specifies the object type, eg:

public String submit(@PathVariable Integer numberOfKeys)

Now if numberOfKeys is not an Integer it will throw an Exception which you can catch using the example given in this answer: https://stackoverflow.com/a/15431466/3415090

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