 |
|
 |
hi,
how do make a statement validate(stating at school books)?
for instance, i ask the user to input.
Name:
Class:
unit of subject:
School books?: (if the user does not want school books, it will jump the question to library card)
how many?:
library card:(if user doesnt want debit card, it will jump to total payment)
how long?
total payment:
appreciate anyone who help me..
thanks
blackboxer
|
|
|
|
 |
|
 |
Do you mean java, or javascript ? If the latter, try the web development forum. If the former, we don't have anything for Java here.
Christian Graus - Microsoft MVP - C++
Metal Musings - Rex and my new metal blog
"I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )
|
|
|
|
 |
|
 |
If you validate the value at client side ,why not use:
<INPUT TYPE="TEXT" NAME="logon_name" VALUE="" VALIDATOR=".......">
Please pardon my weak English!
|
|
|
|
 |
|
 |
I just happened to come across the code written by Christian, and I must say it comes as a great help to me. But I still have a problem with the date format, since the referred code validates mm/dd/yyyy while I need dd/mm/yyyy
I tried to see if I could change some settings in Isdate()but I couldn't figure out where this format is declared. I'm obviously new to js.
I'd appreciate your help.
Premy
|
|
|
|
 |
|
 |
If someone want a new code with many bugs fixed and a lot of features, mail me to omar(nospam)(@)ennec(nospam).______net
features.
mail an date support
select support with many bug fixed
check box validation
background color
and other features.
Bye
Thanks Christian, great code
|
|
|
|
 |
|
 |
my new code:
- email validation.
- radiobutton validation.
- check validation.
- Realy int validation.
- strings validation with alphanumeric, alphabetical or all char allowed.
- select validation with not valid support.
- date with "/" or "-" separator.
and...
- background color in error.
Sorry but I´m spanish and the comments are in Spanish
/***********************************************************************************************************
* *
* Funcion realizada por Omar Sanchez, ENNEC soluciones (www.ennec.net) *
* A raiz de un Javascript encontrado en el web, www.codeproject.com *
* Distribuida bajo licencia GPL *
* *
************************************************************************************************************
* *
* *
* Esta funcion checkea los campos de un formulario segun una forma predefinida. Para que la funcion sepa *
* como ha de tratar cada campo, deberemos de poner un campo tipo hidden indicando su trato. *
* *
* Sintaxis: *
* <input type="text" name=""> *
* <input type="hidden" name="CHK_" *
* value="[|][||][|]||"> *
* *
* NOTA: Los campos ,,,, son insensibles a MAYUSCULAS *
* *
* + tipo: *
* · STR : cadena, indica codificacio ALF->Alfabetica, ALN->Alfanumerica, ALL->Cualquiera *
* <input type="hidden" name="CHK_" value="str|||||"> *
* · INT : numero entero. *
* <input type="hidden" name="CHK_" value="int||||"> *
* · FLOAT : numero decimal. *
* <input type="hidden" name="CHK_" value="float||||"> *
* · DATE : fecha (DD/MM/YYYY Ó DD-MM-YYYY). *
* <input type="hidden" name="CHK_" value="date||||"> *
* · MAIL : checkea que el campo tenga al menos una "@" y un ".", dos caracteres antes de la "@", entre *
* la "@" y el "." al menos dos caracteres y al menos dos caracteres tras el punto y el final *
* <input type="hidden" name="CHK_" value="mail||"> *
* · CHECK : Solo tiene un parametro que es TRUE o FALSE para caso como Acepto las condiciones. *
* <input type="hidden" name="CHK_" value="check||"> *
* · RADIO : Solo tiene un parametro que es TRUE o FALSE para obligar a que selecciones uno o no *
* <input type="hidden" name="CHK_" value="radio||"> *
* · SEL : admite el parametro de obligacion asi como uno de campo no valido para la tipica division *
* o para indicar que el primer campo no es valido si es un "Selecciona uno" indicar *
* un valor para no valido identico a los value del option no valido. *
* <input type="hidden" name="CHK_" value="sel|||"> *
* *
* + min/max: *
* · Valor minimo/maximo. En caso de ser una fecha, minima/maxima fecha admitidas. *
* *
* + obligado: *
* · Admite true y false para indicar si el campo es obligatorio o no rellenarlo. *
* *
* + Nombre del campo: *
* · Nombre para referirse al campo en los mensajes. *
* *
* *
* Para cargar las funciones de checkeo utilizar el siguiente codigo: *
* *
* <script language="JavaScript" src="formvalidator.js"></script> *
* *
* *
* A la hora de chekear el formulario antes de hacer el submit se ha de poner un boton en la forma: *
* *
* <Input type="button" value="PULSAME" önClick="CheckForm(this.form);> *
* *
***********************************************************************************************************/
function CheckForm(form)
{
var i;
var x;
var j;
var okis;
var arr; //para guardar el array de opciones.
var str; //variable con el valor del campo a checkear.
var campo_error = ""; //variable para el campo del error.
var error = ""; //variable para los errores.
var campo; // variable del campo a checkear.
var bgcolor = "#FFFFFF"; // color normal de los diversos campos.
var bgerror = "#FFFF99"; // color para campos erroneos.
var salto = "\n"; //para modificar facilmente el salto de linea en cada error.
var previo = "- "; //un previo a cada linea de error.
for (i=0;i<form.elements.length;i++)
{
if(form.elements[i].name.substr(0,4) == "CHK_")
{
str = GetFieldValueByName(form,form.elements[i].name.substr(4));
if(str != null)
{
campo=GetFieldByName(form,form.elements[i].name.substr(4));
for (x=0;x parseInt(arr[3]))
{
error = error + previo + "El valor del campo " + arr[5] + " es demasiado largo" + salto ;
if (!campo_error){campo_error=campo};
campo.style.background = bgerror;
}
}
break;
case "INT":
//check mandatory field
if (str.length == 0){
if (arr[3].toUpperCase() == "TRUE")
{
error = error + previo + "El campo " + arr[4] + " es obligatorio" + salto ;
if (!campo_error){campo_error=campo};
campo.style.background = bgerror;
}
}
else{
//check sanity
if(!(IsNumeric(str)))
{
error = error + previo + "El valor del campo " + arr[4] + " debe ser numerico" + salto ;
if (!campo_error){campo_error=campo};
campo.style.background = bgerror;
}
else
if(!(IsINT(str)))
{
error = error + previo + "El valor del campo " + arr[4] + " debe ser un entero" + salto ;
if (!campo_error){campo_error=campo};
campo.style.background = bgerror;
}
//check min value
else
if (arr[1] != "x")
{
if (parseInt(str) < parseInt(arr[1]))
{
error = error + previo + "El valor del campo " + arr[4] + " es demasiado bajo" + salto ;
if (!campo_error){campo_error=campo};
campo.style.background = bgerror;
}
}
//check max length
else
if (arr[2] != "x")
{
if (parseInt(str) > parseInt(arr[2]))
{
error = error + previo + "El valor del campo " + arr[4] + " es demasiado alto" + salto ;
if (!campo_error){campo_error=campo};
campo.style.background = bgerror;
}
}
}
break;
case "FLOAT":
str= Replace(str,",",".");
//check mandatory field
if (str.length == 0){
if (arr[3].toUpperCase() == "TRUE")
{
error = error + previo + "El campo " + arr[4] + " es obligatorio" + salto ;
if (!campo_error){campo_error=campo};
campo.style.background = bgerror;
}
}
else{
//check sanity
if(!(IsNumeric(str)))
{
error = error + previo + "El valor del campo " + arr[4] + " debe ser numerico" + salto ;
if (!campo_error){campo_error=campo};
campo.style.background = bgerror;
}
//check min value
else
if (arr[1] != "x")
{
if (parseFloat(str) < parseFloat(arr[1]))
{
error = error + previo + "El valor del campo " + arr[4] + " es demasiado bajo" + salto ;
if (!campo_error){campo_error=campo};
campo.style.background = bgerror;
}
}
//check max length
else
if (arr[2] != "x")
{
if (parseFloat(str) > parseFloat(arr[2]))
{
error = error + previo + "El valor del campo " + arr[4] + " es demasiado alto" + salto ;
if (!campo_error){campo_error=campo};
campo.style.background = bgerror;
}
}
}
break;
case "RADIO":
//check mandatory field
if (arr[1].toUpperCase() == "TRUE")
{
for (x=0;x<form.elements.length;x++) //necesitamos buscar por todos los campos
{
if (form.elements[x].name == campo.name && form.elements[x].checked)
{ //si se llaman igual, miramos si estan checkeados o no
okis="TRUE"; //si lo estan,marcamos la salida como correcta
}
}
if (!okis){ //ninguno estaba marcado :(
error = error + previo + "Es obligatorio seleccionar una accion en el campo " + arr[2] + salto ;
if (!campo_error){campo_error=campo};
for (x=0;x GetDate(arr[2],"/")) || (GetDate(str,"-") > GetDate(arr[2],"/"))) || ((GetDate(str,"/") > GetDate(arr[2],"-")) || (GetDate(str,"-") > GetDate(arr[2],"-"))))
{
error = error + previo + "La fecha del campo " + arr[4] + " es posterior a la fecha maxima admitida" + salto ;
if (!campo_error){campo_error=campo};
campo.style.background = bgerror;
}
}
}
break;
}
}
}
}
if (error)
{
alert (error);
campo_error.focus();
return false;
}
else {
//form.submit();
alert("TODO CORRECTO");
return true;
}
}
//============================================================================================
function Replace(string,replacechar,replacewith)
{
var temp = "";
var i;
string = '' + string;
splitstring = string.split(replacechar);
for(i = 0; i < splitstring.length; i++)
{
if(i < (splitstring.length -1))
temp += splitstring[i] + replacewith;
else
temp += splitstring[i];
}
return temp;
}
//============================================================================================
function GetFieldValueByName(form,name)
{
var i;
for (i=0;i<form.elements.length;i++)
{
if(form.elements[i].name == name)
return (form.elements[i].value);
}
return null;
}
function GetFieldByName(form,name)
{
var i;
for (i=0;i= '0')) ||
(str.charAt(i) == ' ') || (str.charAt(i) == '.') || (str.charAt(i) == ',') || (str.charAt(i) == '-')))
return(false);
}
return(true);
}
//============================================================================================
function IsAlphaNumeric(str)
{
var i;
for(i=0;i= '0')) ||
((str.charAt(i) <= 'z') && (str.charAt(i) >= 'a')) ||
(str.charAt(i) == ' ') || (str.charAt(i) == '-') ||
(str.charAt(i) == 'ü') || (str.charAt(i) == 'ä') ||
(str.charAt(i) == 'ö') || (str.charAt(i) == 'Ü') ||
(str.charAt(i) == 'Ä') || (str.charAt(i) == 'Ö') ||
(str.charAt(i) == 'é') || (str.charAt(i) == 'ß') ||
((str.charAt(i) <= 'Z') && (str.charAt(i) >= 'A')) ))
return(false);
}
return(true);
}
//============================================================================================
function IsAlpha(str)
{
var i;
for(i=0;i= 'a')) ||
(str.charAt(i) == ' ') || (str.charAt(i) == '-') ||
(str.charAt(i) == 'ü') || (str.charAt(i) == 'ä') ||
(str.charAt(i) == 'ö') || (str.charAt(i) == 'Ü') ||
(str.charAt(i) == 'Ä') || (str.charAt(i) == 'Ö') ||
(str.charAt(i) == 'é') || (str.charAt(i) == 'ß') ||
((str.charAt(i) <= 'Z') && (str.charAt(i) >= 'A')) ))
return(false);
}
return(true);
}
//============================================================================================
function Trim(str)
{
//trim leding spaces
while(true)
{
if(str.charAt(0) == ' ')
str = str.substr(1);
else
break;
}
//trim trailing spaces
while(true)
{
if(str.charAt(str.length-1) == ' ')
str = str.substr(0,str.length-1);
else
break;
}
return(str);
}
//============================================================================================
function IsDate(argDate,token)
{
var date_split;
var i;
var tdate, tmonth, tyear;
date_split = argDate.split(token);
//check for date parts
if(date_split.length != 3)
return(false);
//check for zero values
for(i=0;i 1)
{
var pindex = theStr.indexOf(".",index);
if ((pindex > index+2) && (theStr.length > pindex+2))
return true;
}
return false;
}
function IsINT(entero)
{
for (var i = 0; i < entero.length; i++) {
if (entero.charAt(i) < "0" || entero.charAt(i) > "9") {
return false;
}
}
return true;
}
// ------------------------- end of code ------------------------------
|
|
|
|
 |
|
 |
d00d!!!
congratulation!! i mean your idea is great!! WOW who would it thought to paste 15?? pages of js code in here HA! and comented in spanish!! y0u RoX0r man!!!
if y0u n33d me h4lp em@il mi at: ib37_n01_c4n(-)FilterM3Email(@)something._____com
i got an english-spanish dictionary!!
sorry i'm making fun of you!
---------------
Horatiu CRISTEA
|
|
|
|
 |
|
 |
How do I make the script work with the date-formaet DD-MM-YYYY?
Anybody?
|
|
|
|
 |
|
 |
Just change the IsDate() function according to your needs.
e.g. change the
date_split = argDate.split('/');
to
date_split = argDate.split('-');
to have the '-' as delimiter
-cat
|
|
|
|
 |
|
 |
Does anybody know how to change the script, so that the field containing the error will be focus'ed when clicking "OK"?
Maybe something like "form.arr[4].focus()" could be used just before "Return.False"? I can't make it work...
Thanx in advance.
AllanE
|
|
|
|
 |
|
 |
Use the line below instead of "form.arr[4].focus()" as that line points to the hidden field and not the actual form field.
Add this line before return false;
eval(form.name+"."+form.elements[i].name.substr(4)+".focus();");
Hope this helps
|
|
|
|
 |
|
 |
Or you could use this code to place focus on the field that returns an error....
Add this line before return false;
form.elements[i-1].focus()
Happy Coding
|
|
|
|
 |
|
 |
I have added another feature and I think others might be interested as well: TIME. It will check for both military and 24h formats. Please email me at bronnem@wellsfargo.com if you would like me to send the formvalidator.js file to you.
|
|
|
|
 |
|
|
 |
|
 |
I have - perhaps this is a unique situation - a form with a checkbox to disable validation.
Is there a way to do this using your validation routine? Other than that, it's a great script for basic uses (it fills all my needs!).
Thanks
|
|
|
|
 |
|
 |
Well, you can modify the CheckDocument() method. Before you start validation the controls there, you check for your special "disable control".
Cheers
Chris
|
|
|
|
 |
|
 |
I'm doing a survey in asp and need to make sure the user selects a radio button that has a range from 1-5.
|
|
|
|
 |
|
 |
Just change the GetFieldValueByName to the following:
function GetFieldValueByName(form,name)
{
var isRadio = false;
for (var i=0;i<form.elements.length;i++)
{
var formElement = form.elements[i];
if( formElement.name == name )
{
if( formElement.type == "radio" )
isRadio = true;
if( (formElement.type != "radio") || formElement.checked )
return formElement.value;
}
}
if( isRadio )
return ''; else
return null; }
Apologies if that wrapped. Anyway, you can then just treat the radio field as a string, with all of the usual mandatory checking.
Mal.
|
|
|
|
 |
|
 |
It's good implementation and I appreciate you effort.
However, it's not very flexibile and too restriting.
Instead, use of regular expression and expando proerty will allow you to have validate any pattern and very flexible.
|
|
|
|
 |
|
 |
Nice suggestion but regular expressions and so forth would inhibit cross browser compatibility
Thanks Christian - very useful code - I have been toying with the idea of a reuseable/dynamic javascript system for a while - you havew just given me the kick start I needed muchos gracious senor
|
|
|
|
 |
|
 |
Well. You are wong when you say regular expressions and expando properties inhibit cross browser compatability. These techniques are supported by both IE5+ and Netscpae 6+.
|
|
|
|
 |
|
 |
Hi all,
I wouldn' consider IE5+/NS6+ support real browser independence. From my experience support for 4+ versions is a common requirement. So you have to sort out things with NS4.
On the other side it is true that regular expressions give you a great deal of flexibility. However, and that's probably the beauty of the approach, I think it would be an easy thing to modify the concept that it supports reg expressions instead of passing four parameters.
The only problem I see here is the fact (and that's another reason I did not use that approach) that it's more difficult to generate these expressions on the fly from some meta data definition.
Chris
|
|
|
|
 |
|
 |
I am not sure we are in 2002. A high school kid can crack into this kind of validation. Javascript validation is OK (for a better article look at www.apple.com and somewhere under web design they have a better clean solution) but is only OK. You have to do back end checking.
|
|
|
|
 |