PHP JavaScript Form Validation: Output form validation JavaScript from a INI file

Recommend this page to a friend!
  Info   View files Example   Demos   View files View files (8)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog (1)    
Last Updated Ratings Unique User Downloads Download Rankings
2020-08-03 (1 month ago) RSS 2.0 feedNot yet rated by the usersTotal: 193 This week: 18All time: 8,377 This week: 17Up
Version License PHP version Categories
jsclass 0.1GNU General Publi...5HTML, PHP 5, Validation
Description Author

This class can output form validation JavaScript from a INI file.

It can read a given configuration file in the INI format that defines values like the form name, the form field names, validation rules for each field and patterns of character sequences to simplify the definition of common rules for each form field.

The class can generate JavaScript for the form validation code to be outputted as part of the current PHP script output or generate a separate JavaScript for use in a HTML page to be edited separately.

Innovation Award
PHP Programming Innovation award nominee
July 2020
Number 2
Many applications need to generate and validate forms. Usually they generate JavaScript to validate the form values before the form is submitted to the server.

This class provides means to define validation rules as a separate files in the INI format.

This possibility simplifies the building and maintenance of form based Web applications, as developers can easily find the different files that are used to process forms and define form validation rules.

Manuel Lemos
Picture of Pierre FAUQUE
  Performance   Level  
Name: Pierre FAUQUE <contact>
Classes: 14 packages by
Country: France France
Age: 73
All time rank: 16511 in France France
Week rank: 14 Up2 in France France Up
Innovation award
Innovation award
Nominee: 8x

Winner: 1x

Details
                                       JS Class
                             Version 0.1 of jul 17, 2020

                             -----===oooOO$OOooo===-----


PHP allows you to verify a submitted form. However, this is not the right solution
because a succession of errors can lead to multiple exchanges between client and server
and therefore, overload the server and generate unnecessary network traffic. All that
can be verified on the client side must be verified BEFORE submission, leaving to PHP
(server side) as few checks as possible. And this is the role of Javascript.

Any form submitted should therefore be verified by Javascript BEFORE submission. The role
of this class (JS Class) is to generate the Javascript allowing to check the data capture
of a form before submission. This class can be used in two ways :

- either be included in the web page to generate the verification script in
  this page at the right chosen place,
- or be used separately to generate the verification script whose code will be copied
  after generation then pasted in the page concerned, without or with modifications,
  if required.

A member of the class allows to select the mode of use :
$tocopy = 0; : includes JS Class in the page and generates the script when necessary
$tocopy = 1; : generate the "isolated" script to copy it then paste into the web page

The characteristics of this form and the checks to be carried out will be described in
a text file (with ini extension) which will be used by JS Class to generate all the
necessary javascript on the fly (include) or in advance (generation + Copy/Paste).

Let a registration form be an example :
   <form method="post" name="subscription" action="..." onsubmit="return verif()">
The file (ini) describing this form must have for name, the name of the form ;
that is to say, for this example: subscription.ini

HTML fields for keyboarding in a form can be of different types
- text
- password
- textarea
- select
- radio
- checkbox

Except the fields that we click on them (radio, checkbox, buttons, etc.) or that we
select (select), the fields of type "text" in which we make input, may contain
names, email addresses, numbers, dates, etc. The file of description of the form
will make the necessary distinctions for this same "text" type to perform the
checks based on the expected content.

+---------------------+-----------------------+
|      name of        |       name of         |
| types in HTML input | types in formname.ini |
+---------------------+-----------------------+
| password            | text                  |
| text                | text                  |
| text                | date                  |
| text                | hour                  |
| text                | mail                  |
| text                | num                   |
| select              | list                  |
| radio               | radio                 |
| checkbox            | checkbox              |
+---------------------+-----------------------+

+-----------+---------------+------------+------------+--------+--------+---------+---------+--------------------------------------+
| fieldname | field label   | field type | compulsory | lg min | lg max | val min | val max | example : list of [fields]           |
+-----------+---------------+------------+------------+--------+--------+---------+---------+--------------------------------------+
| lname     | Last name     | text       |     1|0    |      2 |     25 |         |         | lname,Last name,text,1,2,25          |
| fname     | First name    | text       |     1|0    |      2 |     25 |         |         | fname,First name,text,1,2,25         |
| bdate     | Birthdate     | date       |     1|0    |        |        |         |         | bdate,Birthdate,date,0               |
| idcity    | City          | list       |     1|0    |        |        |         |         | idcity,City,list,1                   |
| mail      | Mail address  | mail       |     1|0    |      6 |     55 |         |         | mail,Mail address,mail,1,6,55        |
| price     | Selling price | num        |     1|0    |      1 |      6 |       1 |  999.99 | price,Selling price,num,1,6,1,999.99 |
| study     | Study level   | radio      |     1|0    |        |        |         |         | study,Study level,radio,0            |
| ok        | Validation    | valid      |     1|0    |        |        |         |         | ok,Validation,valid,1                |
| sp1;sp2;..| Sports        | checkbox   |     1|0    |        |        |         |         | judo;ski;foot,Sports,checkbox,1      |
| prefh     | Prefered hour | hour       |     1|0    |        |        |         |         | prefh,Prefered hour,1                |

NB: The limit values are excluded. Example
    - price,Selling price,1,3,6,100,500 means : "100 < price < 500" and not "100 <= price <= 500"
    If you want include these limits, modify the class line 371
    If you do not want to check these limit values, do not enter these values or, if you write them, set them to 0.

    Maybe in a future version "val min" and "val max" could be applied for date and time type fields. 


DESCRIPTION OF THE FORM.INI FORM DEFINITION FILE
(for example: subscription.ini)
------------------------------------------------

NB: In this file, all blank lines or starting with a semicolon ; or with a sharp # are
    considered as comments and are ignored.

It includes several sections (the name of the sections can be indifferently written
in upper or lower case):
- [form]
- [general]
- [fields]
- [chars]

For coding reasons and to avoid weighing down the script with multiple tests
(you are developers), there will be no space in different cases when the line :
- will be in the format : "name=value". No spaces around the = following the name of the field.
  Examples:
     name=subscription
     hour=4
     email=ascii + digits + "@ -_ +."
- will be in a list format : No spaces around the commas. Example:
     fieldname,labelname,fieldtype,compulsory(1)-or-not(0),lgmin,lgmax,valmin,valmax

#
# subscription.ini
#
[form]
; This section contains the name of the form (name used by javascript) :
name=subscription

[general]
; This section contains the name of the country, designated by its Top Level Domain (TLD)
; for checking dates according to the date format of the indicated country
; the date formats were collected from https://fr.wikipedia.org/wiki/Date
ctrydate=fr
; This section will accept other values during class work.
; during debugging these will be visible using the debug() method :
; $script = new js("subscription");
; $script->debug();
; The hours can be with 4 digits (HH:MN) or with 6 digits (HH:MN:SS) without spaces
; If hours have to be checked, indicate the number of digits
hour=4

[fields]
; This section contains one line by form control with the following :
; - field name of the input control
; - field label (in the HTML form showed to the Internet user)
; - field type according to JS Class (indicated above)
; - compulsory entry (=1) or not (=0)
; - minimum number of characters
; - maximum number of characters
; - minimum value
; - maximum value
; Example:
bday,birthday,date,1
email,eMail Address,mail,0,6,50
cont,Contribution,num,1,3,6,100,500
; in the above example: compulsory number, 1 to 6 characters (decimal separator included), between $100 and $500
; don't indicate lgmin and lgmax if you don't want to check the length
; except the field label which can contain spaces, there will be no space surrounding the commas
; If there are several check boxes to check, the input names of the check boxes will take the place of field
; name and will be separated by semicolons ( ; ). No spaces around the semicolons. Example:
ski;volley;soccer;swim;none,Sports,checkbox,1

[chars]
; This section contains the characters authorized for each of the fields in which a keyboarding
; will be performed (excluding radio buttons, checkbox, select/list). You can find :
; - ascii (abcdefghijklmnopqrstuvwxyz)
; - letters (abcdefghijklmnopqrstuvwxyz)
; - digits (0123456789)
; - additional characters to add in inverted commas
; If in the used language other accented characters exist, add them to the $letters member of the class.
lname=letters + "' -"
email=ascii + digits + "@-_+."
phone=digits + ".- +"
comment=letters + digits + "&\"' ()[]{}-_\\@+-*/?!,.;/:\n\$%="
; For security reasons, in comment type fields avoid > and < which are also redirection signs
; You can forget the authorized characters for dates and times : a regular expression tests them.
; NB : no space around the first =

USE OF THE CLASS
================

NB: The presence of the compulsory fields will automatically be checked. Optional fields will be ignored
if they have not been keyboarded. But if an entry has been made, the validity (characters allowed,
length, format, etc.) will be checked and will generate an error message if not compliant.

1) inclusion in the page containing the form to be checked
----------------------------------------------------------

By default, the class generates javascript that will be enough to copy and paste it at the right place.
If you want to include the script instead of pasting the javascript, you will have to set
the member $tocopy to 0. This can be done during the instantiation such as :
   $script = new js("subscription",0);
written at the place you want to generate the script (see example2.php file)
Naturally the description file of the form (ex: subscription.ini) must have been created
and uploaded into the directory of the page which contains the form to be checked

2) Copy/Paste javascript into the page containing the form to be checked
------------------------------------------------------------------------

After describing the form (ex: subscription.ini), create a small script such as:
   <?php
   require ("class.js.php");
   $script = new js("subscription"); // $tocopy being set to 1 by default
   ?>
name it (for example) gen_script.php and in a browser type the URL of it :
   http://www.yourwebsite.com/gen_script.php
Copy the generated script from the web page and paste it into the desired location on your page.

On the shell command line (Linux), you can type : php gen_script.php > verif.js
Then, you can integrate it into your page in the desired location with :
   <?php require("verif.js"); ?>
or copy and past the lines of the javascript at the right place.
*

TOOLS
=====

Three methods are public:
- debug()
- fmtdate()
- fmthour()
If JS Class was instantiated with a $script variable :
   $script = new js("subscription");

- $script->debug()   : will display the tables used by JS Class
- $script->fmtdate() : will display the format of the expected date (input help)
- $script->fmthour() : will display the format of the expected time (input help)
(NB: for the last two methods see the file example2.php)


LATEST INFORMATION
==================

You can test the result at the Demo page on the tab "Demos".
Feel free to contact me if needed (help, bugs, improvement, etc.) at :
   pierre@fauque.net



Paris, on july 17, 2020.
  At my demo pagesExternal page  

Open in a separate window

  Files folder image Files  
File Role Description
Plain text file class.js.php Class Main Class
Accessible without login Plain text file subscription.ini Data description of the form
Accessible without login Plain text file example1.html Example Example 1 (copy/paste)
Accessible without login Plain text file example2.php Example Example 2 (include class)
Accessible without login Plain text file gen_script.php Appl. Use to generate code (copy/paste)
Accessible without login Plain text file class.doc.en.txt Doc. English documentation
Accessible without login Plain text file class.doc.fr.txt Doc. French documentation
Accessible without login Plain text file README.txt Data About author and Class

 Version Control Unique User Downloads Download Rankings  
 0%
Total:193
This week:18
All time:8,377
This week:17Up

For more information send a message to info at phpclasses dot org.