info:form_validation_with_js_flexible_oreilly_script

Form Validation with JS: flexible Oreilly Script

<SCRIPT LANGUAGE="JavaScript1.1">
// A utility function that returns true if a string contains only 
// whitespace characters.

function isblank(s)
{
    for(var i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
    }
    return true;
}
// This is the function that performs form verification. It will be invoked
// from the onSubmit() event handler. The handler should return whatever
// value this function returns.

function verify(f)
{
    var msg;
    var empty_fields = "";
    var errors = "";


    // Loop through the elements of the form, looking for all 
    // text and textarea elements that don't have an "optional" property
    // defined. Then, check for fields that are empty and make a list of them.
    // Also, if any of these elements have a "min" or a "max" property defined,

    // then verify that they are numbers and that they are in the right range.
    // Put together error messages for fields that are wrong.
    for(var i = 0; i < f.length; i++) {
        var e = f.elements[i];
        if (((e.type == "text") || (e.type == "textarea")) && !e.optional) {
            // first check if the field is empty

            if ((e.value == null) || (e.value == "") || isblank(e.value)) {
                empty_fields += "\n          " + e.name;
                continue;
            }
            // Now check for fields that are supposed to be numeric.
            if (e.numeric || (e.min != null) || (e.max != null)) { 
                var v = parseFloat(e.value);
                if (isNaN(v) || 
                    ((e.min != null) && (v < e.min)) || 
                    ((e.max != null) && (v > e.max))) {
                    errors += "- The field " + e.name + " must be a number";
                    if (e.min != null) 
                        errors += " that is greater than " + e.min;
                    if (e.max != null && e.min != null) 
                        errors += " and less than " + e.max;
                    else if (e.max != null)
                        errors += " that is less than " + e.max;
                    errors += ".\n";
                }
            }
        }
    }
    // Now, if there were any errors, then display the messages, and

    // return false to prevent the form from being submitted. Otherwise
    // return true.
    if (!empty_fields && !errors) return true;
    msg  = "______________________________________________________\n\n"
    msg += "The form was not submitted because of the following error(s).\n";
    msg += "Please correct these error(s) and re-submit.\n";
    msg += "______________________________________________________\n\n"
    if (empty_fields) {
        msg += "- The following required field(s) are empty:" 
                + empty_fields + "\n";
        if (errors) msg += "\n";
    }
    msg += errors;
    alert(msg);
    return false;
}
</SCRIPT>
<!------------------------------------------------------------------------
     Here's a sample form to test our verification with. Note that we
     call verify() from the onSubmit() event handler, and return whatever
     value it returns. Also note that we use the onSubmit() handler as
     an opportunity to set properties on the form objects that verify()
     will use in the verification process. 
-------------------------------------------------------------------------->

<FORM onSubmit="
    this.firstname.optional = true;
    this.phonenumber.optional = true;
    this.zip.min = 0;
    this.zip.max = 99999;
    return verify(this);
">
First name: <INPUT TYPE=text NAME="firstname">
Last name: <INPUT TYPE=text NAME="lastname"><BR>
Address:<BR><TEXTAREA NAME="address" ROWS=4 COLS=40></TEXTAREA><BR>
Zip Code: <INPUT TYPE=text NAME="zip"><BR>

Phone Number: <INPUT TYPE=text NAME="phonenumber"><BR>
<INPUT TYPE=submit>
</FORM>
<SCRIPT LANGUAGE="JavaScript1.1">
// A utility function that returns true if a string contains only 
// whitespace characters.

function isblank(s)
{
    for(var i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
    }
    return true;
}
// This is the function that performs form verification. It will be invoked
// from the onSubmit() event handler. The handler should return whatever
// value this function returns.

function verify(f)
{
    var msg;
    var empty_fields = "";
    var errors = "";


    // Loop through the elements of the form, looking for all 
    // text and textarea elements that don't have an "optional" property
    // defined. Then, check for fields that are empty and make a list of them.
    // Also, if any of these elements have a "min" or a "max" property defined,

    // then verify that they are numbers and that they are in the right range.
    // Put together error messages for fields that are wrong.
    for(var i = 0; i < f.length; i++) {
        var e = f.elements[i];
        if (((e.type == "text") || (e.type == "textarea")) && !e.optional) {
            // first check if the field is empty

            if ((e.value == null) || (e.value == "") || isblank(e.value)) {
                empty_fields += "\n          " + e.name;
                continue;
            }
            // Now check for fields that are supposed to be numeric.
            if (e.numeric || (e.min != null) || (e.max != null)) { 
                var v = parseFloat(e.value);
                if (isNaN(v) || 
                    ((e.min != null) && (v < e.min)) || 
                    ((e.max != null) && (v > e.max))) {
                    errors += "- Le champ " + e.name + " doit être un chiffre";
                    if (e.min != null) 
                        errors += " supérieur à " + e.min;
                    if (e.max != null && e.min != null) 
                        errors += " et inférieur à  " + e.max;
                    else if (e.max != null)
                        errors += " inférieur à  " + e.max;
                    errors += ".\n";
                }
            }
        }
    }

 value = document.forms[0].email.value;
  var regex = /^((\"[^\"\f\n\r\t\v\b]+\")|([\w\!\#\$\%\&'\*\+\-\~\/\^\`\|\{\}]+(\.[\w\!\#\$\%\&'\*\+\-\~\/\^\`\|\{\}]+)*))@((\[(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))\])|(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))|((([A-Za-z0-9\-])+\.)+[A-Za-z\-]+))$/;
  if (!regex.test(value)) {
        errors += 'Vous devez saisir une adresse email valide\n';
  }



    // Now, if there were any errors, then display the messages, and

    // return false to prevent the form from being submitted. Otherwise
    // return true.
    if (!empty_fields && !errors) return true;
    msg  = "______________________________________________________\n\n"
    msg += "Le formulaire n'a pas été soumis à cause des erreurs suivantes:\n";
    msg += "Merci de corriger et de soumettre à nouveau\n";
    msg += "______________________________________________________\n\n"
    if (empty_fields) {
        msg += "- Les champs obligatoires suivants ne sont pas renseignés:" 
                + empty_fields + "\n";
        if (errors) msg += "\n";
    }
    msg += errors;
    alert(msg);
    return false;
}
</SCRIPT>
<!------------------------------------------------------------------------
     Here's a sample form to test our verification with. Note that we
     call verify() from the onSubmit() event handler, and return whatever
     value it returns. Also note that we use the onSubmit() handler as
     an opportunity to set properties on the form objects that verify()
     will use in the verification process. 
-------------------------------------------------------------------------->

<FORM onSubmit="
    this.firstname.optional = true;
    this.phonenumber.optional = true;
    this.zip.min = 0;
    this.zip.max = 99999;
    return verify(this);
">
First name: <INPUT TYPE=text NAME="firstname">
Last name: <INPUT TYPE=text NAME="lastname"><BR>
Address:<BR><TEXTAREA NAME="address" ROWS=4 COLS=40></TEXTAREA><BR>
Zip Code: <INPUT TYPE=text NAME="zip"><BR>

Phone Number: <INPUT TYPE=text NAME="phonenumber"><BR>
<INPUT TYPE=submit>
</FORM>

Autres validations

value=document.forms[0].tel.value;
 /*var re = /[^0123456789]/gi;*/ 
  var re = /[\.-/ ]/gi; 
 
 var numCleaned=value.replace(re,''); 
/* if (!isNaN(parseInt(value))) {*/
 if (!!isNaN(numCleaned)) {
        errors += "Votre numéro de téléphone " +numCleaned +" contient des données non-numériques.\n";
 }
 if(numCleaned.length< 10){
       errors += "Votre numéro de téléphone " +value +" ne contient pas assez de chiffres (" +numCleaned.length +").\n";
  } 

pour valider une date avec javascript:

<head>
<title>Document sans titre</title>
<script language="JavaScript">
<!--
//PLF- http://www.jejavascript.net/
	function verifdt(){
verdat=document.myform.dateop.value;
datej= new Date()
anneej=datej.getFullYear()+"*";
anneej=anneej.substring(0,2)

if (verdat.length ==6) 
verdat=verdat.substring(0,2)+"/"+verdat.substring(4,2)+"/"+anneej+verdat.substring(6,4);

if (verdat.length ==8) 
verdat=verdat.substring(0,2)+"/"+verdat.substring(4,2)+"/"+verdat.substring(8,4);


if(!isValidDate(verdat))
alert("la date n'est pas valide ou n'est pas au bon format.\n format : jjmmaa ou jjmmaaaa ou jj/mm/aaaa");
else
document.myform.dateop.value = verdat;


	}

	function isValidDate(d) {
var dateRegEx = /^((((0?[1-9]|[12]\d|3[01])[\.\-\/](0?[13578]|1[02])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|[12]\d|30)[\.\-\/](0?[13456789]|1[012])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|1\d|2[0-8])[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|(29[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00)))|(((0[1-9]|[12]\d|3[01])(0[13578]|1[02])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|[12]\d|30)(0[13456789]|1[012])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|1\d|2[0-8])02((1[6-9]|[2-9]\d)?\d{2}))|(2902((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00))))$/;
return d.match(dateRegEx);
	} 
 //-->
</script>
</head>


              <form method="post" action="#" name="myform">
                  <input name="dateop" type="text"  onBlur="verifdt();" maxlength="10">
              </form>
</body>
</html>
/* Prix */
var prix="x";
	for (i=0;i<document.forms[0].Prix.length;i++) {
	if (document.forms[0].Prix[i].checked) {
		prix = document.forms[0].Prix[i].value;
	}
	}

	if(isNaN(prix)) { 
        errors += '- Please specify your fee\n';
	}

calculer_la_somme_de_plusieurs_champs_additions_avec_js

récupérer les valeurs d'un champ checkbox multiple avec php

  • info/form_validation_with_js_flexible_oreilly_script.txt
  • Dernière modification : 2018/07/18 09:45
  • de radeff