简体   繁体   中英

Play Framework: How do I validate for empty text box

I am working on Play Framework 2 for Java and I was trying to validate the text box in my form so I used @Required , It was working fine if we are not entering anything inside the text box but when we are typing spaces on text box then it fails. In short we can say its not trimming the text box value. I also tried @NotNull but it was also not working any more. Please help to out of it.

Introduce an extra validation annotation that checks whether the input matches a non-whitespace regular expression:

@Required
@Pattern("[\\S]+")
public String name;
  • \\s is a shorthand character class that matches a whitespace character
  • \\S is the negated version of this that matches a non-whitespace character
  • + indicates we need at least one non-whitespace character for a match
  • Finally, the backslash needs escaping in Java syntax.

If you just want to prevent users from entering only white spaces into the text field, you can use:

    @Constraints.Required
    @Formats.NonEmpty
    public String name;

The accepted solution will not validate if you have white spaces in between your words. If that's what you want, then it's ok.

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