elp
elp

Reputation: 870

Spring validation: regex annotation does not work

When executing the controller method I receive this log:

OBJECT: [Field error in object 'catalog' on field 'name': rejected value [safasf]; codes [Pattern.catalog.name,Pattern.name,Pattern.java.lang.String,Pattern]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [catalog.name,name]; arguments []; default message [name],[Ljavax.validation.constraints.Pattern$Flag;@5f32f731,org.springframework.validation.beanvalidation.SpringValidatorAdapter$ResolvableAttribute@2180fe7e]; default message [muss auf Ausdruck "[A-Za-z]" passen]]

Regex: [A-Za-z]

Input: safasf

The code:

...
@NotNull
    @Size(min=1, max=8)
    @Pattern(regexp = "[A-Za-z]")
    private String name;
...

The controller:

@PostMapping(ADD_CATALOG)
public String addCatalog(@Valid @ModelAttribute Catalog catalog, BindingResult result){
    if(result.hasErrors()){
        logAction("addCatalog", "Validation of "+catalog.getName()+" failed: ", result.getAllErrors().toString());
        return "redirect:/catalog/addCatalog/";
    }
    catalogProviderComponent.addOrUpdateCatalogEntity(catalogComponent.catalog2catalogEntity(catalog));
    logAction("addCatalog","catalog", catalog);
    return "redirect:/catalog/addCatalog/";
}

When I go to regex101.com everything seems to be fine. Beside that I tried few regex but none seem to work out properly.

Upvotes: 1

Views: 7827

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521073

To allow for one or more lowercase or uppercase letter, you should append + to the end of the pattern:

@NotNull
@Size(min=1, max=8)
@Pattern(regexp = "[A-Za-z]+")
private String name;

Upvotes: 7

Related Questions