Rodrigo G Rodrigues
Rodrigo G Rodrigues

Reputation: 461

Username Validation Java

I'm new in Java, so I don't know very good the language. I have a simple HTML Form to fill register for Login.

My problem is a detail in the username, it can't have some invalid character (accents and symbols, for example) and I don´t know how to check the username characters.

I used request.getParameter("username") to get username in a String variable.

String username = request.getParameter("username");

How can I proceed?

Upvotes: 2

Views: 19135

Answers (2)

Ankur Pathak
Ankur Pathak

Reputation: 1

Use this Bean Validation library:

https://github.com/ankurpathak/username-validation https://mvnrepository.com/artifact/com.github.ankurpathak.username/username-validation

It has all constraints for google like username validation and many more.

Library has different constraint to deal with username validation:

  1. UsernamePattern to allow a-z,0-9,period and underscore characters. These characters can we turned off with some flags in constraints like includePeriod, includeUnderscore and useDigit
  2. EndWithAlphabet to check if username end with alphabet
  3. StartWithAlphabet to check if username start with alphabet
  4. StartWithAlphaNumeric to check username start with alphanumeric
  5. EndWithAlphaNumeric to check username end with alphanumeric
  6. NotContainConsecutivePeriod to check username not contain consecutive period
  7. NotContainConsecutiveUnderscore to check username not contain consecutive underscore
  8. NotContainPeriodFollowedByUnderscore to check username not contain period followed by underscore
  9. NotContainUnderscoreFollowedByPeriod to check username not contain underscore followed by period

All the constraints by default ignore blank so that it will be reposted separately by NotBlank standard bean validation constraint and same can we turned of using ignoreBlank(true by default) flag of each constraint. So google like username can be achieved by:

        @UsernamePattern
        @StartWithAlphaNumeric
        @NotContainConsecutivePeriod
        @EndWithAlphaNumeric
        @NotBlank
        private String username;

Upvotes: 0

Tobías
Tobías

Reputation: 6297

A simple way is the String#matches(String regex) function:

boolean matches(String regex)
Tells whether or not this string matches the given regular expression.

String username = request.getParameter("username");
boolean valid = (username != null) && username.matches("[A-Za-z0-9_]+");

but if this is to be used multiple times is more efficient to use a Pattern:

Pattern pattern = Pattern.compile("[A-Za-z0-9_]+");

and use it each time:

boolean valid = (username != null) && pattern.matcher(username).matches();

Upvotes: 10

Related Questions