0

I have an Entity bean and one of its String-type properties has a @Size annotation as follows:

@PSanityCheck
@Size(min = 8, max = 8, message = "validation.servicecode_length")
@NotEmptyData
@Column(name = "servicecode")
@Field
private String servicecode= "";

However, if I type a string containing a whitespace in the beginning, for example " 1234567" it will accept it as input made of 8 characters. How to make it trim off the whitespace? Is there an annotation for that? The UI is made with Vaadin-framework.

Neil Stockton
  • 11,383
  • 3
  • 34
  • 29
Steve Waters
  • 3,348
  • 9
  • 54
  • 94

1 Answers1

2

You can use the @Pattern annotation with a regular Expression for this

  • 1
    However, the leading whitespace will end up in your database, and that is probably not, what you want. – running hedgehog Jan 03 '17 at 16:27
  • is there a way to make a regular expression to trim the leading whitespace too? – Steve Waters Jan 03 '17 at 16:28
  • 1
    Validation is not the right Approach here. Annotations like @ Size and @ Pattern will only enforce, that the data is in the right format already and cause an exception if it is not. The most general way to check and alter data before persistence is to implement a method with the @ PrePersist annotation in your entity and make necessary changes there. – running hedgehog Jan 03 '17 at 16:37
  • 2
    Personally, I believe that it is cleaner, to ensure that no malformatted strings arrive at your entity bean in the business layer of your application. – running hedgehog Jan 03 '17 at 16:40
  • I think you're right. I found a way to do that in Vaadin. Not sure if this question is helpful, though, with a answer based on Vaadin-framework. – Steve Waters Jan 03 '17 at 16:41
  • 1
    I suggest you put your solution here as a comment for anyone who is reading this question. Have a good day! – running hedgehog Jan 03 '17 at 16:42
  • In Vaadin you add a BlurListener onto the TextField. It is triggered before validation: textField.addBlurListener(e -> { AbstractTextField c = ((AbstractTextField) e.getComponent()); if (c.getValue() != null) { c.setValue(c.getValue().trim()); } }); – Steve Waters Jan 03 '17 at 17:31