I am trying to do a simple form validation in perl dancer but I was wondering what would be the best way to validate simple parameters (e.g. field cannot be empty, validity of the email, minimum length of a field) in dancer/perl without any extra plugin or CPAN module

1 Answer
1

I'm not sure why you'd want to expressly avoid using a plugin or a CPAN module - any solution you come up with will likely do the the same things as a plugin and/or CPAN module except that since it's new code it won't be as mature and tested.

I've recently started using Dancer to develop a simple app and I'll describe how I'm solving this problem using CPAN modules. You may of course choose to ignore it.

The valid_input function is a helper I created for my app, which uses the Data::Form::Validator module from CPAN. The '/usr/add' argument is the name of the validation profile to use - which for simplicity I decided to keep the same as the route name.

I won't bore you with the details of calling Data::Form::Validator since the documentation is pretty good. What I will mention is that in the event that validation fails, the valid_input helper stores away the validation error messages for display in an alert box and also saves the submitted parameters:

thank you for your reply. Well the reason why I wanted to avoid a cpan modules is that in Ruby it would take me 1 line per field e.g. email validation if self.email == '' errors << 'email cannot be blank' elsif !(email !=~ /\A\Z|\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i) errors << 'email must have a valid format' is it really that complicate to do the same thing in perl e.g. another template, cpan module + separate file to define the validation criteria? I just want to be sure I am not missing something as simple as in ruby... thanks
–
devnullSep 10 '12 at 3:54

If you really think it's that easy in Ruby, then you can do it the exact same way in Perl. Instead of errors << 'message here' in Perl you might say add_error('message here') and define the add_error helper function to push messages onto a global array. Ultimately that's what Data::Form::Validator is doing, but in a more structured and reusable way (e.g.: it has a rule for email addresses so you don't need a regex). Also in my view it simplifies the logic to have one helper that returns a full set of valid input or nothing at all.
–
Grant McLeanSep 10 '12 at 4:18

grant, thank you so much. If I am not asking too much and to the benefit of other future viewers could you refine your reply with a sample validation using data::validator as follow (username, email, password, motivation) assuming username check should be existing, email the sytnax and existing, password matching 2 fields and motivation a certain length? I think it would be helfpful! If is too much asked I understand
–
devnullSep 11 '12 at 0:55