suite à mes réflexion sur la poo en javascript
j'en suis rrivé à faire un proto de formulaire autovérifé
plus besoin d'écrire de procédures complexe un lien sur un fichier js et un appel à initForm au démarage et c'est fini.

j'en ai profité pour ajouter un handler pour marquer en rouge les champs invalides et en vert les champs valide. mais cela n'est nullement necessaire.
je vous le donne brut de fonderie.
il reste à intégrer d'autres types de vérification.
mais le coeur de la chose est déjà Ok

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=windows-1250">
  <meta name="generator" content="PSPad editor, www.pspad.com">
  <title></title>
  <script type="text/javascript" language="javascript" src="AutoForm.js"></script>
  <script type="text/javascript" language="JavaScript">
    function isValidated (id) {
      document.getElementById('l'+id).style.backgroundColor='#d6f6c6';
    }
    function isUnvalidated (id) {
      document.getElementById('l'+id).style.backgroundColor='#f6d6c6'
    }
    function init() {
      initForm('myForm',isValidated,isUnvalidated);
      //initForm('myForm');
    }
  </script>
  </head>
  <body onLoad="init();">
<form id="myForm" onSubmit="alert(this.verify()); return false;">
<pre>
  <label for="nom"       id="lnom"       >nom :       <input type="text"    DAP:checkType="NameOrNull"      id="nom"       name="nom"       value="Terrien" size="50"></label> nom, Nom ou NOM (pas NoM)
  <label for="prenom"    id="lprenom"    >prenom :    <input type="text"    DAP:checkType="FirstNameOrNull" id="prenom"    name="prenom"    value="Jean-Yves" size="50"></label> prénom, Prénom-Compose
  <label for="adresse"   id="ladresse"   >mail :      <input type="text"    DAP:checkType="EmailOrNull"     id="adresse"   name="adresse"   value="pierre.dubois@domain.name.com" size="50"></label>
  <label for="telephone" id="ltelephone" >telephone : <input type="text"    DAP:checkType="PhoneOrNull"     id="telephone" name="telephone" value="01 56 95 81 33" size="50"></label>
  <label for="prix"      id="lprix"      >nombre :    <input type="text"    DAP:checkType="NumberOrNull"    id="prix"      name="prix"      value="123,4576" size="50"></label>
  <label for="autre"     id="lautre"     >rien :      <input type="text"                                    id="autre"     name="autre"     value="n'importe quoi" size="50"></label> pas de vérif
  <label for="at"        id="lat"        >expr :      <input type="text"    DAP:checkEreg="^@.*$"           id="at"        name="at"        value="@machinchose" size="50"></label> Match "^@.*$"
  <label for="same"      id="lsame"      >comme :     <input type="text"    DAP:CheckSameAs="nom"           id="same"      name="same"      value="Terrien" size="50"></label>Comme le champs Nom
  <label for="select"    id="lselect"    >option :    <select               DAP:checkType="Number"          id="select"    name="select"    value="">
  <option value="" selected="selected">Faites un choix</option>
  <optgroup id="grp1" xml:lang="fr" label="choisir">
  <option value="1">Un</option>
  <option value="2">Deux</option>
  </optgroup>
  <optgroup id="grp2" xml:lang="en" label="choice">
  <option value="a">One</option>
  <option value="b">Two</option>
  </optgroup>
  </select></label>Option
  <label for="check1"    id="lcheck1"><input type="checkbox" DAP:checkFromTo="2,3"   id="check1" name="checkbox[]" value="1" />Check 1</label>  <label for="radio1"    id="lradio1"><input type="radio"    DAP:checkOne="selected" id="radio1" name="radio" value="1" />Radio 1</label>
  <label for="check2"    id="lcheck2"><input type="checkbox"                         id="check2" name="checkbox[]" value="2" />Check 2</label>  <label for="radio2"    id="lradio2"><input type="radio"                            id="radio2" name="radio" value="2" />Radio 2</label>
  <label for="check3"    id="lcheck3"><input type="checkbox"                         id="check3" name="checkbox[]" value="2" />Check 3</label>
  <label for="check4"    id="lcheck4"><input type="checkbox"                         id="check4" name="checkbox[]" value="2" />Check 4</label>
  <label for="check5"    id="lcheck5"><input type="checkbox"                         id="check5" name="checkbox[]" value="2" />Check 5</label>
  <input type="submit" name="Ok"> <input type="reset">
</pre>
</form>
  </body>
</html>
et le javascript qui vas avec et lui n'a pas besoin d'être modifié seulement enrichi au fin des usages.
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
// JavaScript Document
function initForm (aform, isValidated, isUnvalidated) {
  theform = document.getElementById(aform);
  theform.setAttribute('hasHandler',0);
 
  // Form verify function
  theform.verify = function () {
    res = true;
    elements = theform.elements;
    for(var i = 0; i < elements.length; i++) {
      //alert(elements[i].name+" => "+elements[i].verify);
      res = res & elements[i].verify();
    }
 
    hasHandler = this.getAttribute('hasHandler');
    if ((res == 0) && (hasHandler==0)) {
      alert ("Un ou plusieurs champs de ce formulaire ne sont pas valides.");
      this.style.backgroundColor='#f6d6c6';
    } else if (hasHandler==0) {
      this.style.backgroundColor='#d6f6c6';
    }
    return res;
  }
 
  // Default handlers
  this.isValidated = function () {}
    if (typeof(isValidated) == 'function') {
    this.isValidated = isValidated;
    theform.setAttribute('hasHandler',1);
  }
 
  this.isUnvalidated = function () {}
    if (typeof(isUnvalidated) == 'function') {
    this.isUnvalidated = isUnvalidated;
    theform.setAttribute('hasHandler',1);
  }
 
  // Matching methods
  this.eregMatch = function () {
    ereg=this.getAttribute('DAP:checkEreg');
    if (typeof(ereg) == 'string') {
      modele = new RegExp(ereg);
      //alert(this.name+"=>"+modele);
      res = modele.test(this.value);
      if (res && this.id) {
        this.isValidated(this.id);
      } else {
        this.isUnvalidated(this.id);
      }
      return res;
    } else {
      return true;
    }
  }
 
  this.isNumber = function () {
    //064343,56465 876.5757
    this.setAttribute('DAP:checkEreg', '^[0-9]*(\\.|,)?[0-9]+$');
    return this.eregMatch();
  }
 
  this.isNumberOrNull = function () {
    //064343,56465 876.5757 NULL
    this.setAttribute('DAP:checkEreg', '^[0-9]*(\\.|,)?[0-9]+$|^$');
    return this.eregMatch();
  }
 
  this.isPhone = function () {
    //01.23.45.67.89 0 123 456 789
    this.setAttribute('DAP:checkEreg', '^[0-9]{2}(\\.| )?[0-9]{2}(\\.| )?[0-9]{2}(\\.| )?[0-9]{2}(\\.| )?[0-9]{2}$|^[0-9]{1}(\\.| )?[0-9]{3}(\\.| )?[0-9]{3}(\\.| )?[0-9]{3}$');
    return this.eregMatch();
  }
 
  this.isPhoneOrNull = function () {
    //01.23.45.67.89 0 123 456 789 NULL
    this.setAttribute('DAP:checkEreg', '^[0-9]{2}(\\.| )?[0-9]{2}(\\.| )?[0-9]{2}(\\.| )?[0-9]{2}(\\.| )?[0-9]{2}$|^[0-9]{1}(\\.| )?[0-9]{3}(\\.| )?[0-9]{3}(\\.| )?[0-9]{3}$|^$');
    return this.eregMatch();
  }
 
  this.isEmail = function () {
    //prenom.nom@sousdomain.domain.ext
    this.setAttribute('DAP:checkEreg', '^[0-9a-zA-Z_\-]+(\\.)?[0-9a-zA-Z_\-]*@([0-9a-zA-Z_-]+\\.)+[a-zA-Z]{2,3}$');
    return this.eregMatch();
  }
 
  this.isEmailOrNull = function () {
    //prenom.nom@sousdomain.domain.ext NULL
    this.setAttribute('DAP:checkEreg', '^[0-9a-zA-Z_\-]+(\\.)?[0-9a-zA-Z_\-]*@([0-9a-zA-Z_-]+\\.)+[a-zA-Z]{2,3}$|^$');
    return this.eregMatch();
  }
 
  this.isName = function () {
    //Nom nom NOM (Pas NoM)
    this.setAttribute('DAP:checkEreg', '^[A-Z]?[a-zßàáâãäåæçèéêëìíîïðñòóôõöùúûüýÿ]+$|^[A-Z]+$');
    return this.eregMatch();
  }
 
  this.isNameOrNull = function () {
    //Nom nom NOM NULL (Pas NoM)
    this.setAttribute('DAP:checkEreg', '^[A-Z]?[a-zßàáâãäåæçèéêëìíîïðñòóôõöùúûüýÿ]+$|^[A-Z]+$|^$');
    return this.eregMatch();
  }
 
  this.isIdentFT = function () {
    //idft1234 IDFT1234
    this.setAttribute('DAP:checkEreg', '^[a-zA-Z]{4}[0-9]{4}$');
    return this.eregMatch();
  }
 
  this.isIdentFTOrNull = function () {
    //idft1234 IDFT1234
    this.setAttribute('DAP:checkEreg', '^[a-zA-Z]{4}[0-9]{4}$|^$');
    return this.eregMatch();
  }
 
  this.isFirstName = function () {
    //Prénom prénom PRENOM-COMPOSE (Pas PréNom)
    this.setAttribute('DAP:checkEreg', '^[A-Z]?[a-zßàáâãäåæçèéêëìíîïðñòóôõöùúûüýÿ]+(-[A-Z]?[a-zßàáâãäåæçèéêëìíîïðñòóôõöùúûüýÿ]+)?$|^[A-Z]+(-[A-Z]+)?$');
    return this.eregMatch();
  }
 
  this.isFirstNameOrNull = function () {
    //Prénom prénom PRENOM-COMPOSE NULL (Pas PréNom)
    this.setAttribute('DAP:checkEreg', '^[A-Z]?[a-zßàáâãäåæçèéêëìíîïðñòóôõöùúûüýÿ]+(-[A-Z]?[a-zßàáâãäåæçèéêëìíîïðñòóôõöùúûüýÿ]+)?$|^[A-Z]+(-[A-Z]+)?$|^$');
    return this.eregMatch();
  }
 
  this.isSameAs = function () {
    if (typeof(this.getAttribute('DAP:CheckSameAs'))== 'string') {
      res = this.value == document.getElementById(this.getAttribute('DAP:CheckSameAs')).value;
      if (res && this.id) {
        this.isValidated(this.id);
      } else {
        this.isUnvalidated(this.id);
      }
      return res;
    } else {
      return true;
    }
  }
 
  this.checkOne = function () {
    name = this.getAttribute('name');
    colection = document.getElementsByName(name);
    res = false;
    for(var i = 0; i < colection.length; i++) {
      //alert (colection[i].checked);
      res = res | colection[i].checked;
    }
 
    for(var i = 0; i < colection.length; i++) {
      if (res && colection[i].id) {
        colection[i].isValidated(colection[i].id);
      } else {
        colection[i].isUnvalidated(colection[i].id);
      }
    }
 
    return res;
  }
 
  this.checkFromTo = function () {
    if (typeof(this.getAttribute('DAP:checkFromTo'))== 'string') {
      minmax = this.getAttribute('DAP:checkFromTo');
      tab = minmax.split(',');
      //alert (tab[0]+" => "+tab[1]+" "+tab);
    } else {
      return true;
    }
    name = this.getAttribute('name');
    colection = document.getElementsByName(name);
    count = 0;
    for(var i = 0; i < colection.length; i++) {
      //alert (colection[i].checked);
      if ( colection[i].checked) count++;
    }
    res = (tab[0] <= count) && (count <= tab[1]);
    for(var i = 0; i < colection.length; i++) {
      if (res && colection[i].id) {
        colection[i].isValidated(colection[i].id);
      } else {
        colection[i].isUnvalidated(colection[i].id);
      }
    }
 
    return res;
  }
 
  // Form elements verify binding  
  elements = theform.elements;
  if (elements[0]) elements[0].focus();
 
  for(var i = 0; i < elements.length; i++) {
    if (elements[i].getAttribute('DAP:checkType')) {
      if (typeof(eval('this.is'+elements[i].getAttribute('DAP:checkType'))) == 'function') {
        elements[i].verify = eval('this.is'+elements[i].getAttribute('DAP:checkType'));
        elements[i].eregMatch = this.eregMatch;
      } else {
        elements[i].verify = this.eregMatch;
      }
    } else if (elements[i].getAttribute('DAP:CheckSameAs')) {
      elements[i].verify = this.isSameAs;
    } else if (elements[i].getAttribute('DAP:checkOne')) {
      elements[i].verify = this.checkOne;
    } else if (elements[i].getAttribute('DAP:checkFromTo')) {
      elements[i].verify = this.checkFromTo;
    } else {
      elements[i].verify = this.eregMatch;
    }
    elements[i].isValidated = this.isValidated;
    elements[i].isUnvalidated = this.isUnvalidated;
  }
}
A+JYT
Citation Envoyé par note
je n'ais pas fait poster le formulaire dans l'exemple. il faut changer
Code : Sélectionner tout - Visualiser dans une fenêtre à part
onSubmit="alert(this.verify()); return false;"
par
Code : Sélectionner tout - Visualiser dans une fenêtre à part
onSubmit="return this.verify();"
Il est compatible IE et FireFox
Il tien compte des spécifitées DOM (plutôt que des objets IE)

Il n’existe qu’une seule fonction initForm les autres sont intégrée dans « l’objet » initForm ceci enlève d’éventuels conflits avec des fonctions existantes.

Une fonction isNumber peut exister elle ne sera pas remise en cause par ce fichier js

les tag de vérif sont de la forme
DAP:checkType="NumberOrNull"

Methodes de vérification de bouton radio et boites à cocher
ajout des tags
DAP:SameAs qui prend pour valeur l'id du champ à comparer
"doit avoir la même valeur que le champs indiqué" utile pour les confirmation de password par exemple

DAP:checkOne="selected" (seule et unique valeur possible) pour les checkbox ou les radios oblige à avoir un élément sélectionné dans la collection.

DAP:checkFromTo="min,max" pour les boite à cocher le groupe doit avoir au moins nin coches et au plus max coches sélectionnées.

DAP:checkType fonctionne avec les options