/lib/HTML/FormHandler/Field/Email.pm

http://github.com/gshank/html-formhandler · Perl · 82 lines · 66 code · 15 blank · 1 comment · 3 complexity · 92038571added6686d6ba898cde01a67 MD5 · raw file

  1. package HTML::FormHandler::Field::Email;
  2. # ABSTRACT: validates email using Email::Valid
  3. use HTML::FormHandler::Moose;
  4. extends 'HTML::FormHandler::Field::Text';
  5. use Email::Valid;
  6. our $class_messages = {
  7. 'email_format' => 'Email should be of the format [_1]',
  8. };
  9. has '+html5_type_attr' => ( default => 'email' );
  10. has 'email_valid_params' => (
  11. is => 'rw',
  12. isa => 'HashRef',
  13. );
  14. has 'preserve_case' => (
  15. is => 'rw',
  16. isa => 'Bool',
  17. );
  18. sub get_class_messages {
  19. my $self = shift;
  20. return {
  21. %{ $self->next::method },
  22. %$class_messages,
  23. }
  24. }
  25. apply(
  26. [
  27. {
  28. transform => sub {
  29. my ( $value, $field ) = @_;
  30. return $value
  31. if $field->preserve_case;
  32. return lc( $value );
  33. }
  34. },
  35. {
  36. check => sub {
  37. my ( $value, $field ) = @_;
  38. my $checked = Email::Valid->address(
  39. %{ $field->email_valid_params || {} },
  40. -address => $value,
  41. );
  42. $field->value($checked)
  43. if $checked;
  44. },
  45. message => sub {
  46. my ( $value, $field ) = @_;
  47. return [$field->get_message('email_format'), 'someuser@example.com'];
  48. },
  49. }
  50. ]
  51. );
  52. =head1 DESCRIPTION
  53. Validates that the input looks like an email address using L<Email::Valid>.
  54. Widget type is 'text'.
  55. If form has 'is_html5' flag active it will render <input type="email" ... />
  56. instead of type="text"
  57. This field has an 'email_valid_params' attribute that accepts a hash
  58. reference of extra values passed to L<Email::Valid/address> when
  59. validating email addresses.
  60. If you want to preserve the case of the email address, set the
  61. 'preserve_case' attribute.
  62. =head1 DEPENDENCIES
  63. L<Email::Valid>
  64. =cut
  65. __PACKAGE__->meta->make_immutable;
  66. use namespace::autoclean;
  67. 1;