Pregunta
¿Cómo validar un formulario con Javascript?
Responder esta pregunta por dudin el 2009-05-22
Tengo que implementar un formulario con los siguientes campos: nombre, correo, teléfono y ciudad. Necesito validar la entrada de los datos (todos son obligatorios) al menos con javascript.
Respuestas
Para validar un formulario con Jquery usando un motor de validación de Cedric Dugas:
http://jquery.validationEngine.js
<form id="formID" class="formular" method="post" action="">
<fieldset>
<legend>User informations</legend>
<label>
<span>Desired username : </span>
<input class="validate[optional,custom[noSpecialCaracters],length[0,20]]" type="text" name="user" id="user" />
</label>
<label>
<span>First name : </span>
<input class="validate[required,custom[onlyLetter],length[0,100]] text-input" type="text" name="firstname" id="firstname" />
</label>
<label>
<span>Last name : </span>
<input class="validate[required,custom[onlyLetter],length[0,100]] text-input" type="text" name="lastname" id="lastname" />
</label>
<div>
<span>Radio Groupe : <br /></span>
<span>radio 1: </span>
<input class="validate[required] radio" type="radio" name="radiogoupe" id="radio1" value="5">
<span>radio 2: </span>
<input class="validate[required] radio" type="radio" name="radiogoupe" id="radio2" value="3"/>
<span>radio 3: </span>
<input class="validate[required] radio" type="radio" name="radiogoupe" id="radio3" value="9"/>
</div>
<div>
<span>Max 2 checkbox : <br /></span>
<input class="validate[minCheckbox[2]] checkbox" type="checkbox" name="checkboxgroupe" id="maxcheck1" value="5">
<input class="validate[minCheckbox[2]] checkbox" type="checkbox" name="checkboxgroupe" id="maxcheck2" value="3"/>
<input class="validate[minCheckbox[2]] checkbox" type="checkbox" name="checkboxgroupe" id="maxcheck3" value="9"/>
</div>
<label>
<span>Date : (format YYYY-MM-DD)</span>
<input class="validate[required,custom[date]] text-input" type="text" name="date" id="date" />
</label>
<label>
<span>Favorite sport 1:</span>
<select name="sport" id="sport" class="validate[required]" id="sport" >
<option value="">Choose a sport</option>
<option value="option1">Tennis</option>
<option value="option2">Football</option>
<option value="option3">Golf</option>
</select>
</label>
<label>
<span>Favorite sport 2:</span>
<select name="sport2" id="sport2" multiple class="validate[required]" id="sport2" >
<option value="">Choose a sport</option>
<option value="option1">Tennis</option>
<option value="option2">Football</option>
<option value="option3">Golf</option>
</select>
</label>
<label>
<span>Age : </span>
<input class="validate[required,custom[onlyNumber],length[0,3]] text-input" type="text" name="age" id="age" />
</label>
<label>
<span>Telephone : </span>
<input class="validate[required,custom[telephone]] text-input" type="text" name="telephone" id="telephone" />
</label>
</fieldset>
<fieldset>
<legend>Password</legend>
<label>
<span>Password : </span>
<input class="validate[required,length[6,11]] text-input" type="password" name="password" id="password" />
</label>
<label>
<span>Confirm password : </span>
<input class="validate[required,confirm[password]] text-input" type="password" name="password2" id="password2" />
</label>
</fieldset>
<fieldset>
<legend>Email</legend>
<label>
<span>Email address : </span>
<input class="validate[required,custom[email]] text-input" type="text" name="email" id="email" />
</label>
<label>
<span>Confirm email address : </span>
<input class="validate[required,confirm[email]] text-input" type="text" name="email2" id="email2" />
</label>
</fieldset>
<fieldset>
<legend>Comments</legend>
<label>
<span>Comments : </span>
<textarea class="validate[required,length[6,300]] text-input" name="comments" id="comments" /> </textarea>
</label>
</fieldset>
<fieldset>
<legend>Conditions</legend>
<div class="infos">Checking this box indicates that you accept terms of use. If you do not accept these terms, do not use this website : </div>
<label>
<span class="checkbox">I accept terms of use : </span>
<input class="validate[required] checkbox" type="checkbox" id="agree" name="agree"/>
</label>
</fieldset>
<input class="submit" type="submit" value="Validate & Send the form!"/>
<hr/>
</form>
http://jquery.validationEngine.js
/*
* Inline Form Validation Engine, jQuery plugin
*
* Copyright(c) 2009, Cedric Dugas
* http://www.position-relative.net
*
* Form validation engine witch allow custom regex rules to be added.
* Licenced under the MIT Licence
*/
$(document).ready(function() {
// SUCCESS AJAX CALL, replace "success: false," by: success : function() { callSuccessFunction() },
$("[class^=validate]").validationEngine({
success : false,
failure : function() {}
})
});
jQuery.fn.validationEngine = function(settings) {
if($.validationEngineLanguage){ // IS THERE A LANGUAGE LOCALISATION ?
allRules = $.validationEngineLanguage.allRules
}else{
allRules = {"required":{ // Add your regex rules here, you can take telephone as an example
"regex":"none",
"alertText":"* This field is required",
"alertTextCheckboxMultiple":"* Please select an option",
"alertTextCheckboxe":"* This checkbox is required"},
"length":{
"regex":"none",
"alertText":"*Between ",
"alertText2":" and ",
"alertText3": " characters allowed"},
"minCheckbox":{
"regex":"none",
"alertText":"* Checks allowed Exceeded"},
"confirm":{
"regex":"none",
"alertText":"* Your field is not matching"},
"telephone":{
"regex":"/^[0-9\-\(\)\ ]+$/",
"alertText":"* Invalid phone number"},
"email":{
"regex":"/^[a-zA-Z0-9_\.\-]+\@([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/",
"alertText":"* Invalid email address"},
"date":{
"regex":"/^[0-9]{4}\-\[0-9]{1,2}\-\[0-9]{1,2}$/",
"alertText":"* Invalid date, must be in YYYY-MM-DD format"},
"onlyNumber":{
"regex":"/^[0-9\ ]+$/",
"alertText":"* Numbers only"},
"noSpecialCaracters":{
"regex":"/^[0-9a-zA-Z]+$/",
"alertText":"* No special caracters allowed"},
"onlyLetter":{
"regex":"/^[a-zA-Z\ \']+$/",
"alertText":"* Letters only"}
}
}
settings = jQuery.extend({
allrules:allRules,
inlineValidation: true,
success : false,
failure : function() {}
}, settings);
$("form").bind("submit", function(caller){ // ON FORM SUBMIT, CONTROL AJAX FUNCTION IF SPECIFIED ON DOCUMENT READY
if(submitValidation(this) == false){
if (settings.success){
settings.success && settings.success();
return false;
}
}else{
settings.failure && settings.failure();
return false;
}
})
if(settings.inlineValidation == true){ // Validating Inline ?
$(this).not("[type=checkbox]").bind("blur", function(caller){loadValidation(this)})
$(this+"[type=checkbox]").bind("click", function(caller){loadValidation(this)})
}
var buildPrompt = function(caller,promptText,showTriangle) { // ERROR PROMPT CREATION AND DISPLAY WHEN AN ERROR OCCUR
var divFormError = document.createElement('div')
var formErrorContent = document.createElement('div')
var arrow = document.createElement('div')
$(divFormError).addClass("formError")
$(divFormError).addClass($(caller).attr("id"))
$(formErrorContent).addClass("formErrorContent")
$(arrow).addClass("formErrorArrow")
$("body").append(divFormError)
$(divFormError).append(arrow)
$(divFormError).append(formErrorContent)
if(showTriangle == true){ // NO TRIANGLE ON MAX CHECKBOX AND RADIO
$(arrow).html('<div class="line10"></div><div class="line9"></div><div class="line8"></div><div class="line7"></div><div class="line6"></div><div class="line5"></div><div class="line4"></div><div class="line3"></div><div class="line2"></div><div class="line1"></div>');
}
$(formErrorContent).html(promptText)
callerTopPosition = $(caller).offset().top;
callerleftPosition = $(caller).offset().left;
callerWidth = $(caller).width()
callerHeight = $(caller).height()
inputHeight = $(divFormError).height()
callerleftPosition = callerleftPosition + callerWidth -30
callerTopPosition = callerTopPosition -inputHeight -10
$(divFormError).css({
top:callerTopPosition,
left:callerleftPosition,
opacity:0
})
$(divFormError).fadeTo("fast",0.8);
};
var updatePromptText = function(caller,promptText) { // UPDATE TEXT ERROR IF AN ERROR IS ALREADY DISPLAYED
updateThisPrompt = $(caller).attr("id")
$("."+updateThisPrompt).find(".formErrorContent").html(promptText)
callerTopPosition = $(caller).offset().top;
inputHeight = $("."+updateThisPrompt).height()
callerTopPosition = callerTopPosition -inputHeight -10
$("."+updateThisPrompt).animate({
top:callerTopPosition
});
}
var loadValidation = function(caller) { // GET VALIDATIONS TO BE EXECUTED
rulesParsing = $(caller).attr('class');
rulesRegExp = /\[(.*)\]/;
getRules = rulesRegExp.exec(rulesParsing);
str = getRules[1]
pattern = /\W+/;
result= str.split(pattern);
var validateCalll = validateCall(caller,result)
return validateCalll
};
var validateCall = function(caller,rules) { // EXECUTE VALIDATION REQUIRED BY THE USER FOR THIS FIELD
var promptText =""
var prompt = $(caller).attr("id");
var caller = caller;
var callerName = $(caller).attr("name");
isError = false;
callerType = $(caller).attr("type");
for (i=0; i<rules.length;i++){
switch (rules[i]){
case "optional":
if(!$(caller).val()){
closePrompt(caller)
return isError
}
break;
case "required":
_required(caller,rules);
break;
case "custom":
_customRegex(caller,rules,i);
break;
case "length":
_length(caller,rules,i);
break;
case "minCheckbox":
_minCheckbox(caller,rules,i);
break;
case "confirm":
_confirm(caller,rules,i);
break;
default :;
};
};
if (isError == true){
var showTriangle = true
if($("input[name="+callerName+"]").size()> 1 && callerType == "radio") { // Hack for radio group button, the validation go the first radio
caller = $("input[name="+callerName+"]:first")
showTriangle = false
var callerId ="."+ $(caller).attr("id")
if($(callerId).size()==0){ isError = true }else{ isError = false}
}
if($("input[name="+callerName+"]").size()> 1 && callerType == "checkbox") { // Hack for radio group button, the validation go the first radio
caller = $("input[name="+callerName+"]:first")
showTriangle = false
var callerId ="div."+ $(caller).attr("id")
if($(callerId).size()==0){ isError = true }else{ isError = false}
}
if (isError == true){ // show only one
($("div."+prompt).size() ==0) ? buildPrompt(caller,promptText,showTriangle) : updatePromptText(caller,promptText)
}
}else{
if($("input[name="+callerName+"]").size()> 1 && callerType == "radio") { // Hack for radio group button, the validation go the first radio
caller = $("input[name="+callerName+ por Anónimo el 2009-07-17
He encontrado una librería Javascript gratis llamada Vanadium, es completamente extensible, personalizable y soporta validación con Ajax.
http://vanadiumjs.com/
http://vanadiumjs.com/
por Anónimo el 2009-09-07
Aquí te dejo un ejemplo usando la librería javascript Protoform que requiere además de la librería javascript Prototype.
- Código de Protoform: http://www.cssrevolt.com/upload/files/protoform/protoform.js
- Para descargar la Prototype: http://www.prototypejs.org/download
- Demo del uso de Protoform: http://www.cssrevolt.com/upload/files/protoform/
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Formulario de contacto</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript" src="protoform.js"></script>
<link href="styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="container">
<div id="box">
<form action="send.php" method="post" id="send" class="validate">
<fieldset>
<legend>Enviar mensaje</legend>
<div>
<label for="name_Req">Nombre<span>*</span></label>
<input type="text" id="name_Req" name="name" title="Por favor! Entre su nombre" />
</div>
<div>
<label for="telephone_Req_Tel">Número telefónico<span>*</span></label>
<input type="text" id="telephone_Req_Tel" name="telephone" title="Entre su número telefónico" />
</div>
<div>
<label for="contact_Req_Email">E-mail<span>*</span></label>
<input type="text" id="contact_Req_Email" name="email" title="Entre una dirección de correo válida" />
</div>
<div>
<label for="city_Req">Ciudad<span>*</span></label>
<input type="text" id="name_Req" name="city" title="Debe entrar el nombre de sus ciudad" />
</div>
<div class="button">
<input type="submit" value="Enviar" />
</div>
</fieldset>
</form>
</div>
</body>
</html>
- Código de Protoform: http://www.cssrevolt.com/upload/files/protoform/protoform.js
- Para descargar la Prototype: http://www.prototypejs.org/download
- Demo del uso de Protoform: http://www.cssrevolt.com/upload/files/protoform/
por Anónimo el 2009-06-09
AQUI DEJO ESTE SCRIPT QUE ENCONTRÉ SOLO ADAPTALO. LO PUSE ENTRE EL HEAD
DESPUES SOLO LLAME EL SCRIPT AL BOTON DE GUARDAR
funcion de validar function validar() { patron=/^[0-9]*$/; if (document.form1.cve_cliente.value == "") { alert ("Por favor introduce la clave, es dato obligatorio"); document.form1.cve_cliente.focus();return; } if (document.form1.responsable.value == "") { alert ("Por favor llene el campo de responsable, no puede ser nulo"); document.form1.responsable.focus();return; } if (document.form1.razon_social.value == "") { alert ("Dato requerido escriba la Razón Social"); document.form1.razon_social.focus();return; } if (form1.direccion.value == "") { alert ("Por favor introduzca la dirección, es dato obligatorio"); document.form1.direccion.focus();return; }
DESPUES SOLO LLAME EL SCRIPT AL BOTON DE GUARDAR
if (document.form1.telefono.value == "") { alert ("El campo de teléfono no puede estar vacío"); document.form1.telefono.focus();return; } if(isNaN(parseInt(document.form1.telefono.value)) || patron.test(document.form1.telefono.value)==0){ alert('El campo de Teléfono solo acepta valores numéricos'); document.form1.telefono.focus();return; } if (form1.correo.value == "") { alert ("Dato Obligatorio, Por favor escriba el correo"); document.form1.correo.focus();return; } document.form1.submit(); }
por Anónimo el 2009-06-09



