0
votes

I am trying to validate the string email to check if it already appears within my MYSQL database, when I execute with an email thats already used I get the following error:

java.lang.IllegalStateException: Invalid target for Validator [co2103.hw2.controller.TestResultsValidator@62b41c6]: org.springframework.validation.BeanPropertyBindingResult: 1 errors Field error in object 'testResults' on field 'email': rejected value [[email protected]]; codes [email.testResults.email,email.email,email.java.lang.String,email]; arguments []; default message [is already provided by a different user! Please user another one!]

Here is the validator code

public class TestResultsValidator implements Validator{
private TestResultsRepository TrRepo;
private HomeTestRepository HTRepo;
public TestResultsValidator (TestResultsRepository TrRepo, HomeTestRepository HTRepo) {
    this.TrRepo = TrRepo;
    this.HTRepo = HTRepo;
}
@Override
public boolean supports(Class<?> clazz) {
    return TestResults.class.equals(clazz);
}

@Override
public void validate(Object target, Errors errors) {

    TestResults tr = (TestResults) target;
    
    for(TestResults t : TrRepo.findAll()) {
        //SAME EMAIL
        if (tr.getEmail().equals(t.getEmail())) {
            errors.rejectValue("email", "email", "is already provided by a different user! Please user another one!");
        System.out.println("Email is already taken by a different user, please try another username");
        break;
        }

The controller code

//Add new results
@RequestMapping(value = "/addResults",method = {RequestMethod.POST , RequestMethod.GET})
public String newHotel(@Valid @ModelAttribute TestResults results, BindingResult result, Model model) {
    if (result.hasErrors()) {
         model.addAttribute("errors", result);
        return "start";
    }
    else {
    trRepo.save(results);
    return "Submitted";
}}
1

1 Answers

0
votes

You need to register you validator to spring.

First ad Component Annotation to your validtor.

@Component
public class TestResultsValidator implements Validator{
.....
}

Register it in the controller.

@Controller
class TestResultController {
    @Autowired
    TestResultsValidator testResultsValidator ;

    @InitBinder("testResultsValidator")
    protected void initMessageBinder(WebDataBinder binder) {
        binder.addValidators(testResultsValidator );
    }
}