0

I'm writing a simple calculator EP, here's the form that I'm using

@AllArgsConstructor
@NoArgsConstructor
@Data
public class CalculatorForm {
    private double leftArg;
    private double rightArg;
    private String operation;

    @AssertTrue(message = "You can't divide by zero!")
    private boolean isValid(){
        return !(operation.equals("/") && rightArg == 0);
    }


    public double getResult() {
        leftArg = switch (operation) {
            case "+" -> {
                yield leftArg + rightArg;
            }
            case "-" -> {
                yield leftArg - rightArg;
            }
            case "*" -> {
                yield  leftArg * rightArg;
            }
            case "/" -> {
//                Assert.isTrue(rightArg != 0, "Can't divide by 0!");
                yield  leftArg / rightArg;
            }
            default -> throw new IllegalStateException("Unexpected operation: " + operation);
        };
        rightArg = 0;
        return leftArg;
    }
}

and now requesting zero division responds with error webpage but I want to use isValid() inside thymeleaf form so that it won't even be allowed to proceed with such request, how can I achieve that?

I've tried to follow this guide but it looks like it works only for fields while my validation is a method

  • 2
    I'm not an expert on Thymeleaf but I'm pretty sure it is doing server-side validation, i.e. the form data is first sent to the Spring Boot backend where an interceptor kicks in and does the validation. You could add your validation either in another interceptor or your controller for an easy solution. Real client-side validation would require code to be executed in the client (i.e. the browser). Html 5 provides some field level validation but for anything more complex you'll very likely need to use JavaScript or any other language supported by the browser. – Thomas Apr 11 '23 at 15:17

0 Answers0