| Rose-HTML-Objects documentation | Contained in the Rose-HTML-Objects distribution. |
Rose::HTML::Form::Field::PhoneNumber::US - Text field that accepts only input that contains exactly 10 digits, and coerces valid input into US phone numbers in the form: 123-456-7890
$field =
Rose::HTML::Form::Field::PhoneNumber::US->new(
label => 'Phone',
name => 'phone',
size => 20);
$field->input_value('555-5555');
# "Phone number must be 10 digits, including area code"
$field->validate or warn $field->error;
$field->input_value('(123) 456-7890');
print $field->internal_value; # "123-456-7890"
print $field->html;
...
Rose::HTML::Form::Field::PhoneNumber::US is a subclass of Rose::HTML::Form::Field::Text that only allows values that contain exactly 10 digits, which it coerces into the form "123-456-7890". It overrides the validate() and inflate_value(), and deflate_value() methods of its parent class.
This is a good example of a custom field class that constrains the kinds of inputs that it accepts and coerces all valid input and output to a particular format. See Rose::HTML::Form::Field::Time for another example, and a list of more complex examples.
John C. Siracusa (siracusa@gmail.com)
Copyright (c) 2010 by John C. Siracusa. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
| Rose-HTML-Objects documentation | Contained in the Rose-HTML-Objects distribution. |
package Rose::HTML::Form::Field::PhoneNumber::US; use strict; use Rose::HTML::Object::Errors qw(:phone); use base 'Rose::HTML::Form::Field::Text'; our $VERSION = '0.606'; __PACKAGE__->add_required_html_attrs( { maxlength => 14, }); sub validate { my($self) = shift; my $number = $self->internal_value; return 1 if($number !~ /\S/); $number =~ s/\D+//g; return 1 if(length $number == 10); $self->add_error_id(PHONE_INVALID); return; } sub inflate_value { my($self, $value) = @_; return unless(defined $value); $value =~ s/\D+//g; if($value =~ /^(\d{3})(\d{3})(\d{4})$/) { return "$1-$2-$3"; } return $_[1]; } *deflate_value = \&inflate_value; if(__PACKAGE__->localizer->auto_load_messages) { __PACKAGE__->localizer->load_all_messages; } use utf8; # The __DATA__ section contains UTF-8 text 1; __DATA__ [% LOCALE en %] PHONE_INVALID = "Phone number must be 10 digits, including area code." [% LOCALE de %] PHONE_INVALID = "Die Telefon-Nummer muà 10 Stellen enthalten (einschlieÃlich Vorwahl)." [% LOCALE fr %] PHONE_INVALID = "Le numéro de téléphone, indicatif compris, doit avoir 10 chiffres." [% LOCALE bg %] PHONE_INVALID = "ТелеÑÐ¾Ð½Ð½Ð¸Ñ Ð½Ð¾Ð¼ÐµÑ (вкл. кода на облаÑÑÑа) не ÑÑÑбва да надвиÑава 10 ÑиÑÑи." __END__