blib/lib/HTML/FormHandlerX/JQueryRemoteValidator.pm

filter: Statementstmt 26.6% 33 / 124 Branchbran 0.0% 0 / 22 Conditioncond 0.0% 0 / 4 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 54.5% 12 / 22 Podpod n/a totaltotal 25.8% 45 / 174 CC 25 SCAR 26.5
CC
25
Cov
22%
__ANON__
27.9
_data_for_validation_spec
27.9
__ANON__
26.3
CRAP 14.2
↑ Summary
1 package HTML::FormHandlerX::JQueryRemoteValidator;
2 2 $HTML::FormHandlerX::JQueryRemoteValidator::VERSION = '0.22';
3 2 ▶use HTML::FormHandler::Moose::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use Method::Signatures::Simple;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use JSON ();
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7  
8 2 has_field _validation_scripts => (type => 'JavaScript', set_js_code => '_js_code_for_validation_scripts');
9  
10 2 has validation_endpoint => (is => 'rw', isa => 'Str', default => '/ajax/formvalidator');
11  
12 2 has jquery_validator_link => (is => 'rw', isa => 'Str', default => 'http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js');
13  
14 1 ▶has skip_remote_validation_types => (is => 'rw', isa => 'ArrayRef', default => sub { [ qw(Submit Hidden noCAPTCHA Display JSON JavaScript) ] });
Subroutine __ANON__: called CC=1 SCAR=0.0
15  
16 2 has skip_all_remote_validation => (is => 'rw', isa => 'Bool', default => 0);
17  
18 2 ▶method _js_code_for_validation_scripts () {
Subroutine BEGIN: called CC=1 SCAR=4.1
Subroutine __ANON__: not called CC=2 SCAR=17.0
Subroutine _js_code_for_validation_scripts: not called CC=2 SCAR=17.0
19 0 my $spec_data = $self->_data_for_validation_spec;
20 0 ▶ my $spec = JSON->new->utf8
Condition0%0/4
'JSON'->new->utf8->allow_nonref->pretty(1)->encode($spec_data) || ''
l!l
00
'JSON'->new->utf8->allow_nonref->pretty(1)->encode($spec_data) || ''
l!l
00
MC/DC0%0/1
'JSON'->new->utf8->allow_nonref->pretty(1)->encode($spec_data) || ''
'JSON'->new->utf8->allow_nonref->pretty(1)->encode($spec_data)
MC/DC0%0/1
'JSON'->new->utf8->allow_nonref->pretty(1)->encode($spec_data) || ''
'JSON'->new->utf8->allow_nonref->pretty(1)->encode($spec_data)
Truth table0%0/2
A
A= 'JSON'->new->utf8->allow_nonref->pretty(1)->encode($spec_data)
Aresult
11
00
Truth table0%0/2
A
A= 'JSON'->new->utf8->allow_nonref->pretty(1)->encode($spec_data)
Aresult
11
00
21 ->allow_nonref
22 ->pretty(1)
23 # ->relaxed(undef)
24 # ->canonical(undef)
25 ->encode($spec_data)
26 || '';
27  
28 0 my $form_name = $self->name;
29 0 $spec =~ s/"${form_name}_data_collector"/${form_name}_data_collector/g;
30 0 $spec =~ s/\n$//;
31 0 $spec = "\n var ${form_name}_validation_spec = $spec;\n";
32 0 return $self->_data_collector_script . $spec . $self->_run_validator_script;
33 2 }
34  
35 2 ▶method _data_for_validation_spec () {
Subroutine BEGIN: called CC=1 SCAR=4.1
Subroutine __ANON__: not called CC=5 SCAR=33.3
Subroutine _data_for_validation_spec: not called CC=5 SCAR=33.3
36 0 my $js_profile = { rules => {}, messages => {} };
37  
38 0 foreach my $f (@{$self->fields}) {
39 0 ▶ next if $self->_skip_remote_validation($f); # don't build rules for these fields
Branch: 2 branches
BranchTrueFalseTotal
if $self->_skip_remote_validation($f) 0 0 0
if $self->_skip_remote_validation($f) 0 0 0
40 0 ▶ if ($f->isa('HTML::FormHandler::Field::Repeatable')) { # also 'Compound' as well but I don't have one of these lying around just yet
Branch: 2 branches
BranchTrueFalseTotal
if ($f->isa('HTML::FormHandler::Field::Repeatable')) { } 0 0 0
if ($f->isa('HTML::FormHandler::Field::Repeatable')) { } 0 0 0
41 0 foreach my $subf (sort {$a->name cmp $b->name} map {$_->fields} $f->fields) {
42 0 $js_profile->{rules}->{$subf->id}->{remote} = $self->_build_remote_rule($subf);
43 }
44 }
45 else {
46 0 $js_profile->{rules}->{$f->id}->{remote} = $self->_build_remote_rule($f);
47 }
48 }
49  
50 0 return $js_profile;
51 2 }
52  
53 2 ▶method _build_remote_rule ($field) {
Subroutine BEGIN: called CC=1 SCAR=3.5
Subroutine __ANON__: not called CC=1 SCAR=4.6
54 0 my $remote_rule = {
55 url => sprintf("%s/%s/%s", $self->validation_endpoint, $self->name, $field->id),
56 type => 'POST',
57 data => $self->name . "_data_collector",
58 };
59  
60 0 return $remote_rule;
61 2 }
62  
63 2 ▶method _data_collector_script () {
Subroutine BEGIN: called CC=1 SCAR=2.6
Subroutine _data_collector_script: not called CC=5 SCAR=32.7
64 0 my @func;
65 0 foreach my $f (sort {$a->name cmp $b->name} $self->fields) { # the sort is for consistent output in tests
66 0 ▶ next if $self->_skip_data_collection($f);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_skip_data_collection($f) 0 0 0
67 0 ▶ if ($f->isa('HTML::FormHandler::Field::Repeatable')) { # also 'Compound' as well but I don't have one of these lying around just yet
Branch: 1 branch
BranchTrueFalseTotal
if ($f->isa('HTML::FormHandler::Field::Repeatable')) { } 0 0 0
68 0 foreach my $subf (sort {$a->name cmp $b->name} map {$_->fields} $f->fields) {
69 0 push @func, sprintf " \"%s\": function () { return \$(\"#%s\").val() }",
70 $subf->id, _escape_dots($subf->id);
71 }
72 }
73 else {
74 0 push @func, sprintf " \"%s\": function () { return \$(\"#%s\").val() }",
75 $f->id, _escape_dots($f->id);
76 }
77 }
78  
79 0 my $form_name = $self->name;
80 0 return " var ${form_name}_data_collector = {\n" . join(",\n", @func) . "\n };\n";
81 2 }
82  
83 sub _escape_dots {
84 0 ▶ my $str = shift;
Subroutine _escape_dots: not called CC=1 SCAR=6.9
85 0 $str =~ s/\./\\\\./g;
86 0 return $str;
87 }
88  
89 2 ▶method _skip_remote_validation ($field) {
Subroutine BEGIN: called CC=1 SCAR=3.5
Subroutine __ANON__: not called CC=4 SCAR=28.5
90 0 ▶ return 1 if $self->skip_all_remote_validation;
Branch: 1 branch
BranchTrueFalseTotal
if $self->skip_all_remote_validation 0 0 0
91 0 my %skip_type = map {$_=>1} @{$self->skip_remote_validation_types};
92 0 ▶ return 1 if $field->get_tag('no_remote_validate');
Branch: 1 branch
BranchTrueFalseTotal
if $field->get_tag("no_remote_validate") 0 0 0
93 0 ▶ return 1 if $skip_type{$field->type};
Branch: 1 branch
BranchTrueFalseTotal
if $skip_type{$field->type} 0 0 0
94 0 return 0;
95 2 }
96  
97 2 ▶method _skip_data_collection ($field) {
Subroutine BEGIN: called CC=1 SCAR=3.5
Subroutine _skip_data_collection: not called CC=2 SCAR=15.4
98 0 ▶ return 0 if $field->type eq 'Hidden'; # collect, but don't validate, hidden fields
Branch: 1 branch
BranchTrueFalseTotal
if $field->type eq "Hidden" 0 0 0
99 0 return $self->_skip_remote_validation($field);
100 2 }
101  
102 2 ▶method _run_validator_script () {
Subroutine BEGIN: called CC=1 SCAR=2.6
Subroutine _run_validator_script: not called CC=2 SCAR=16.4
103 0 my $form_name = $self->name;
104 0 my $link = $self->jquery_validator_link;
105  
106 my $opts = join ",\n ",
107 0 map { sprintf "%s: %s", $_, $self->jquery_validator_opts->{$_} }
108 0 keys %{$self->jquery_validator_opts};
109  
110 0 ▶ $opts = "\n$opts," if $opts;
Branch: 1 branch
BranchTrueFalseTotal
if $opts 0 0 0
111  
112 0 my $script = <<SCRIPT;
113  
114 \$(document).ready(function() {
115 \$.getScript("$link", function () {
116 if (typeof ${form_name}_validation_spec !== 'undefined') {
117 \$('form#$form_name').validate({$opts
118 rules: ${form_name}_validation_spec.rules,
119 submitHandler: function(form) { form.submit(); }
120 });
121 }
122 });
123 });
124 SCRIPT
125  
126 0 return $script;
127 2 }
128  
129 # http://jqueryvalidation.org/validate/ - start reading with the summary at the *end* of the page
130 1 ▶has 'jquery_validator_opts' => (is => 'rw', isa => 'HashRef[Str]', required => 0, default => sub {{}});
Subroutine __ANON__: called CC=1 SCAR=0.0
131  
132  
133  
134  
135  
136  
137 2 1; # End of HTML::FormHandlerX::JQueryRemoteValidator
138  
139 __END__
140  
141 =pod
142  
143 =encoding UTF-8
144  
145 =head1 NAME
146  
147 HTML::FormHandlerX::JQueryRemoteValidator
148  
149 =head1 VERSION
150  
151 version 0.22
152  
153 =head1 SYNOPSIS
154  
155 package MyApp::Form::Foo;
156 use HTML::FormHandler::Moose;
157  
158 with 'HTML::FormHandlerX::JQueryRemoteValidator';
159  
160 ...
161  
162 # You need to provide a form validation script at /ajax/formvalidator
163 # In Poet/Mason, something like this in /ajax/formvalidator.mp -
164  
165 route ':form_name/:field_name';
166  
167 method handle () {
168 my $form = $.form($.form_name);
169 $form->process(params => $.args, no_update => 1);
170  
171 my $err = join ' ', @{$form->field($.field_name)->errors};
172 my $result = $err || 'true';
173  
174 $m->print(JSON->new->allow_nonref->encode($result));
175 }
176  
177 =head1 CONFIGURATION AND SETUP
178  
179 The purpose of this package is to build a set of JQuery scripts and inject them
180 into your forms. The scripts send user input to your server where you must
181 provide an endpoint that can validate the fields. Since you already have an
182 HTML::FormHandler form, you can use that.
183  
184 The package uses the remote validation feature of the JQuery Validator
185 framework. This also takes care of updating your form to notify the user of
186 errors and successes while they fill in the form. You will most likely want
187 to customise that behaviour for your own situation. An example is given below.
188  
189 =head2 What you will need
190  
191 =over 4
192  
193 =item JQuery
194  
195 Load the JQuery library somewhere on your page.
196  
197 =item JQuery validator
198  
199 See the C<jquery_validator_link> attribute.
200  
201 =item Server-side validation endpoint
202  
203 See the C<validation_endpoint> attribute.
204  
205 =item Some JS fragments to update the form
206  
207 =item CSS to prettify it all
208  
209 =back
210  
211 =head2 An example using the Bootstrap 3 framework
212  
213 =head3 Markup
214  
215 <form ...>
216  
217 <div class="form-group form-group-sm">
218 <label class="col-xs-3 control-label" for="AddressForm.name"></label>
219 <div class="col-xs-6">
220 <input type="text" name="AddressForm.name" id="AddressForm.name"
221 class="form-control" value="" />
222 </div>
223 <label for="AddressForm.name" id="AddressForm.name-error"
224 class="has-error control-label col-xs-3">
225 </label>
226 </div>
227  
228 <div class="form-group form-group-sm">
229 <label class="col-xs-3 control-label" for="AddressForm.address"></label>
230 <div class="col-xs-6">
231 <input type="text" name="AddressForm.address" id="AddressForm.address"
232 class="form-control" value="" />
233 </div>
234 <label for="AddressForm.address" id="AddressForm.address-error"
235 class="has-error control-label col-xs-3">
236 </label>
237 </div>
238  
239 ...
240  
241 </form>
242  
243 =head3 CSS
244  
245 Most of the classes on the form come from Twitter Bootstrap 3. In this example,
246 JQuery validator targets error messages to the second <label> on each
247 form-control. This is the default behaviour but can be changed.
248  
249 The default setup will display and remove messages as the user progresses
250 through the form. JQuery Validator offers lots of options. You can read about
251 them at L<http://jqueryvalidation.org/validate/>. You should start by reading
252 the few sentences at the very bottom of that page.
253  
254 Some useful additional styling to get started:
255  
256 label.valid {
257 width: 24px;
258 height: 24px;
259 background: url(/static/images/valid.png) center center no-repeat;
260 display: inline-block;
261 text-indent: -9999px;
262 }
263  
264 label.error {
265 font-weight: normal;
266 color: red;
267 padding: 2px 8px;
268 margin-top: 2px;
269 }
270  
271 =head3 JavaScript
272  
273 You can provide extra JavaScript functions to control the behaviour of the error
274 and success messages in the C<jqr_validate_options> attribute:
275  
276 my $jqr_validate_options = {
277 highlight => q/function(element, errorClass, validClass) {
278 $(element).closest('.form-group').addClass(errorClass).removeClass(validClass);
279 $(element).closest('.form-group').find("label").removeClass("valid");
280 }/,
281 unhighlight => q/function(element, errorClass, validClass) {
282 $(element).closest('.form-group').removeClass(errorClass);
283 }/,
284 success => q/function(errorLabel, element) {
285 $(element).closest('.form-group').addClass("has-success");
286 errorLabel.addClass("valid");
287 }/,
288 errorClass => '"has-error"',
289 validClass => '"has-success"',
290 errorPlacement => q/function(errorLabel, element) {
291 errorLabel.appendTo( element.parent("div").parent("div") );
292 }/,
293 };
294  
295 has '+jqr_validate_options' => (default => sub {$jqr_validate_options});
296  
297 =head2 Class (form) attributes
298  
299 =head3 C<validation_endpoint>
300  
301 Default: /ajax/formvalidator
302  
303 The form data will be POSTed to C<[validation_endpoint]/[form_name]/[field_name]>.
304  
305 Note that *all* fields are submitted, not just the field being validated.
306  
307 You must write the code to handle this submission. The response should be a JSON
308 string, either C<true> if the field passed its tests, or a message describing
309 the error. The message will be displayed on the form.
310  
311 The synopsis has an example for Poet/Mason.
312  
313 =head3 C<jquery_validator_link>
314  
315 Default: http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js
316  
317 You can leave this as-is, or if you prefer, you can put the file on your own
318 server and modify this setting to point to it.
319  
320 =head3 C<jquery_validator_opts>
321  
322 Default: {}
323  
324 A HashRef, keys being the keys of the C<validate> JQuery validator call documented
325 at L<http://jqueryvalidation.org/validate/>, with values being JavaScript functions
326 etc. as described there.
327  
328 =head3 C<skip_remote_validation_types>
329  
330 Default: C<[ qw(Submit Hidden noCAPTCHA Display JSON JavaScript) ]>
331  
332 A list of field types that should not be included in the validation calls.
333  
334 =head3 C<skip_all_remote_validation>
335  
336 Boolean, default 0.
337  
338 A flag to turn off remote validation altogether, perhaps useful during form development.
339  
340 =head2 Field attributes
341  
342 =head3 Tag C<no_remote_validate> [C<Bool>]
343  
344 Default: not set
345  
346 Set this tag to a true value on fields that should not be remotely validated:
347  
348 has_field 'foo' => (tags => {no_remote_validate => 1}, ... );
349  
350 =head1 See also
351  
352 =over 4
353  
354 =item L<http://www.catalystframework.org/calendar/2012/23>
355  
356 =item L<http://alittlecode.com/wp-content/uploads/jQuery-Validate-Demo/index.html>
357  
358 =item L<http://jqueryvalidation.org>
359  
360 =back
361  
362 =head1 ACKNOWLEDGEMENTS
363  
364 This started out as a modification of Aaron Trevana's
365 HTML::FormHandlerX::Form::JQueryValidator
366  
367 =head1 AUTHOR
368  
369 Dave Baird <dave@zerofive.co.uk>
370  
371 =head1 COPYRIGHT AND LICENSE
372  
373 This software is copyright (c) 2016 by David R. Baird.
374  
375 This is free software; you can redistribute it and/or modify it under
376 the same terms as the Perl 5 programming language system itself.
377  
378 =cut
↑ Summary