Solved

PHP Form Buiilder ajax submission and custom vaidation

Posted on 2014-03-01
17
951 Views
Last Modified: 2014-03-25
Hello

I am trying to find a form builder in php which will automatically validate the fields preferably using jquery and allow me to submit the form via ajax.

So far I have been looking at http://www.imavex.com/php-form-builder-class/examples/ajax.php which allows me to submit the form via ajax. However I cannot see an example for this tool which would let me add my own custom validation function. For example I might be registering a new user and want to check that their email address isnt already in the database. I would need to add a custom validation function and error message to the email field and in this instance the validation function would be an ajax call in itself.

Please can anyone provide an example of a custom validation function which adds a specific validation and error message to a specified field. I doesnt matter if the custom function is ajax or not or just client side but an ajax example would be preferable.

I can do this type of validation with the jquery validation plugin so I am presuming it should be possible in these tools. It seems such a common requirement

Many thanks in advance for any help you can give.
0
Comment
Question by:andieje
  • 9
  • 6
17 Comments
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 167 total points
ID: 39897162
It's a common requirement and from the number of PHP web sites that get hacked, it would appear that it's common for developers to overlook it!  You will find parts of this sort of thing in PHP frameworks (Slim and Laravel are gaining traction now, Zend is slipping into irrelevance) and PHP CMS systems (WordPress for simplicity, Drupal for power).  But it's unlikely that you'll find anything that is a general-purpose plugin because there are too many variables to control for.  Consider the email validation process.  If the email passed jQuery validation, it would get submitted to the server where it would be processed through PHP.  First you would use filter_var() to ensure that the field contained a valid email address.  Then you would use a query to check the existence in the data base.  But what would the query say?  What columns would you select?  What data base connection would you use?  What would the logic be if the email already existed in the data base?  What message would you give the client?  What if there are other issues such as a too-easy-to-guess password? It's this sort of thing that makes general-purpose validation complicated and difficult to generalize.  In a framework, many of these things are controlled (see also Ruby on Rails) so convention takes precedence over configuration.

A design pattern that offers some reusability is an abstract class with a validation method for each kind of external input.  Upon receiving an external input the script instantiates the class and sends the request data (in PHP this is easy because the request data always appears in superglobals like $_GET and $_COOKIE).  You can standardize some of the validation process, and you can extend the class for more specialized validation.
0
 

Author Comment

by:andieje
ID: 39897369
Hi

To be honest Ray, I didnt think it would be that difficult. With the jquery validation plugin you can just attach a custom validation function to an input field. The custom function sets the validator attacthed to the form as false if validation fails and the rest of the form is validated as normal. You also configure an error message for the custom function.

I was expecting these form building frameworks with validation to have a similar thing where where you can associate a custom function with a field and if it fails you set the overall isvalid property (or something similar) of the form to false. The form would carry on doing the rest of its validation

This appears to have some custom validation at the bottom of the page

http://www.imavex.com/php-form-builder-class/examples/validation.php

So this is my favourite so far but it isnt as intuitive as the jquery validation plugin.

The reason i dont want to write the validation myself is because the website is all in ajax so sometimes i am overwriting forms with other forms after postback and then having to dynamicaly generate the validation code for the new form and i often get conflicts with the validation from the old form.

to be quite frank its a right pain (especially given as i dont know php or jquery :)
0
 

Author Comment

by:andieje
ID: 39897374
If you have any other ideas of recommendations for a framework I am open to suggestion as I'm not a php developer. I have made wordpress sites but this new site is a totally bespoke site and has to be written from scratch. I'm used to programming in .net and just knocking out forms in a visual window an create database layers using hibernate or soething.

I was going to use fuelphp for my database classes and this form builder for my interface. If you can recommend something else that does the lot or is better for overall goal then that is appreciated.

Thanks a lot
0
 
LVL 26

Expert Comment

by:EddieShipman
ID: 39898659
What we do for our e-commerce application is use the jQuery ValidationEngine (https://github.com/posabsolute/jQuery-Validation-Engine) for client-side validation;
we also use it's ajax validation rules for pre-existence of email addresseses.

We also use our PHP code to check for malformed form data as well.

Our form's are hand built, Why would you need a "form builder"?
0
 

Author Comment

by:andieje
ID: 39901357
I normally use the query validation engine but I am making a massive ajax website and sometimes i find creating the forms dynamically and creating the ajax form validation dynamically can be quite time consuming. If its a non ajax site its mich quicker. I have also found (thought i cant remember specific) examples where the validation from old forms which used to be on the page have conflicted with new forms that have replaced them via ajax calls. So i suppose its an ajax issue?
0
 

Author Comment

by:andieje
ID: 39901457
@eddie - this question might help you see why i dont want to dynamically generate the query

http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28379134.html

Thanks
0
 
LVL 26

Expert Comment

by:EddieShipman
ID: 39901622
I fail to see how that post would make me not want to use it. It is just a simple mistake by that developer of not synchronizing the message with the rule.
0
 

Author Comment

by:andieje
ID: 39903316
@Eddie - point taken

I have also asked this question. Perhaps you would be kind enough to provide a simple example of how you create your form and your query validation dynamically together

Thanks a lot
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 26

Assisted Solution

by:EddieShipman
EddieShipman earned 333 total points
ID: 39903953
As I said, our forms are hand built so not dynamically generated. However, due to the nature of the validation-engine rules, it is possible to dynamically build your form and keep the rules, intact.

All you have to do is add the correct validation class or data-validation-engine attribute on your form fields for the validation-engine to invoke validation for the fields. You can write your own ajax validation rules as well.

Our ajax validation for email and username looks like this:
                "ajaxEmailCheck": {
                    "url": "/json_api/AjaxEmailCheck/",
                    "extraDataDynamic": ['#EmailAddress'],
                    "alertText": "* An Account with this email has already been created.",
                    "alertTextLoad": "* Validating, please wait..."
                },
                "ajaxUserCheck": {
                    "url": "/json_api/AjaxUserCheck/",
                    "extraDataDynamic": ['#Username', '#Password'],
                    "alertText": "* This username is already taken."
                }

Open in new window

Then the form fields that call these looks like this:
<input type="text" name="EmailAddress" id="EmailAddress" value="{embed:EmailAddress}" title="Email Address" maxLength="50" size="50" class="validate[required,custom[email],ajax[ajaxEmailCheck]] register_input"/>
<input type="text" name="Username" id="Username" value="{embed:Username}" title="Username" class="validate[required,minSize[5]maxSize[20],custom[onlyLetNumSpec],notequals[EmailAddress]] register_input" />

Open in new window

0
 

Author Comment

by:andieje
ID: 39912377
@eddie

Thanks a lot. I';ve never seen jquery added like that with the square brackets. Please can you point me to a tutorial that advises on your way of doing it. The extent of my knowledge is basically like the way it is done on this page : http://runnable.com/UZJ24Io3XEw2AABU/how-to-validate-forms-in-jquery-for-validation (you have to drag index.php from the left hand menu into the box)

Also can these rules all be put into some sort of an include that is included in every page or do they have to go in the document ready function. It would be nice to know how to reuse the rules rather than copy and paste them between forms

Many many thanks
0
 

Author Comment

by:andieje
ID: 39912382
Fir example, on your code snippet, lets say you had a number field which didnt have ajax validation and you wanted i to say 'Number only required' how would you do that please?
0
 
LVL 26

Expert Comment

by:EddieShipman
ID: 39913095
The example you posted is for a different plugin. I've used the standard jquery validation plugin and it is a lot more difficult to use and write rules for than the one I posted above.

The square bracket notations are for the jQuery Validation-Engine plugin.

Number only required is a validation that is included in the plugin's rules, use it like this, remember, this validation is for decimal numbers, not integers.
<input type="text" name="MyNumber" id="MyNumber" value="" title="MyNumber" class="validate[required,custom[number]]" />

Open in new window

Use this one for integers only:
<input type="text" name="MyInteger" id="MyInteger" value="" title="MyInteger" class="validate[required,custom[integer]]" />

Open in new window


The 'required'  attribute means that the field is required to validate correctly. Yes the rules are all located in an include. I actually have 2, one for English alert text and one for Spanish alert text. BTW, you can use Regex to write your rules, too. I have modified several of the built in rules to be more efficient.

You can find out more at the URL I posted in comment #39898659.
0
 

Author Comment

by:andieje
ID: 39914599
I'm sorry eddie - i assumed the jquery validation engine plugin was the jquery validation plugin. Thats my mistake for not even following your link in the comment. Can I ask why you prefer the engine one? I will look into this now but presumably you can rewrite reusable rules wit the jquery validation engine plugin. I would really like something where i can have reusable ajax rules and reusable client side rules.
0
 
LVL 26

Expert Comment

by:EddieShipman
ID: 39917557
Yes, you can write your own ajax rules and client-side rules. I prefer it because I feel that it is much easier to use and you can consolidate your rules in one file. I am not entirely sure that the jquery validation plugin let's you do that. Make sure you read the documentation to understand how to setup new rules and to format your validation classes.
The new version also allows setting data attributes on your controls vs. using a class for your rules (https://github.com/posabsolute/jQuery-Validation-Engine#experimental-attribute-data-validation-engine).
0
 

Author Comment

by:andieje
ID: 39929636
Thanks Eddie - I will investigate.

If you dont mind my asking, when building your forms do you just have methods for outputting textboxes, dropdowns etc and call them appropriately
0
 
LVL 26

Accepted Solution

by:
EddieShipman earned 333 total points
ID: 39930821
All my forms are built manually in my HTML code. I don't build them programatically. Well, I do have one popup form that is built dynamically in PHP but it is pretty simple. I just pass the relevant data to the script and it manipulates the HTML that is output to the client based on certain data values. I also use jQuery to manipulate some of my other popup forms based on other data.
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The purpose of this video is to demonstrate how to set up the WordPress backend so that each page automatically generates a Mailchimp signup form in the sidebar. This will be demonstrated using a Windows 8 PC. Tools Used are Photoshop, Awesome…
The viewer will learn how to count occurrences of each item in an array.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now