PageRenderTime 43ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/java/com/samskivert/servlet/user/Username.java

http://github.com/samskivert/samskivert
Java | 68 lines | 36 code | 10 blank | 22 comment | 3 complexity | 1ba0b68e327c89a253c5f748dff3c46e MD5 | raw file
Possible License(s): LGPL-2.1
  1. //
  2. // samskivert library - useful routines for java programs
  3. // Copyright (C) 2001-2012 Michael Bayne, et al.
  4. // http://github.com/samskivert/samskivert/blob/master/COPYING
  5. package com.samskivert.servlet.user;
  6. /**
  7. * Allows us to require a valid username as a parameter without having to
  8. * do the checking ourselves.
  9. */
  10. public class Username
  11. {
  12. /** The minimum allowable length of a username. */
  13. public static final int MINIMUM_USERNAME_LENGTH = 3;
  14. /** The maximum allowable length of a username. */
  15. public static final int MAXIMUM_USERNAME_LENGTH = 12;
  16. /** The regular expression defining valid names. */
  17. public static final String NAME_REGEX = "^[_A-Za-z0-9]*$";
  18. /**
  19. * Creates a username instance.
  20. */
  21. public Username (String username)
  22. throws InvalidUsernameException
  23. {
  24. validateName(username);
  25. _username = username;
  26. }
  27. /** Returns the text of this username. */
  28. public String getUsername ()
  29. {
  30. return _username;
  31. }
  32. @Override
  33. public String toString ()
  34. {
  35. return _username;
  36. }
  37. /**
  38. * Validates our username. The default implementation requires that usernames consist only of
  39. * characters that match the {@link #NAME_REGEX} regular expression and be between {@link
  40. * #MINIMUM_USERNAME_LENGTH} and {@link #MAXIMUM_USERNAME_LENGTH} characters.
  41. */
  42. protected void validateName (String username)
  43. throws InvalidUsernameException
  44. {
  45. // check length
  46. if (username.length() < MINIMUM_USERNAME_LENGTH) {
  47. throw new InvalidUsernameException("error.username_too_short");
  48. }
  49. if (username.length() > MAXIMUM_USERNAME_LENGTH) {
  50. throw new InvalidUsernameException("error.username_too_long");
  51. }
  52. // check that it's only valid characters
  53. if (!username.matches(NAME_REGEX)) {
  54. throw new InvalidUsernameException("error.invalid_username");
  55. }
  56. }
  57. protected String _username;
  58. }