Ago232009

Validar formularios accesibles sin onsubmit

Hace unos meses publiqué un artículo denominado formularios accesibles con javascript, para ello usaba el atributo onsubmit de la etiqueta form para validar el formulario web con javascript.

A continuación, explicaré con un ejemplo como implementar en nuestro desarrollo web, javascript no intrusivo para validar formularios accesibles sin onsubmit.

Ventajas validar formularios accesibles sin onsubmit

  • Se cumplen los estándares web del W3C.
  • Se cumplen las pautas de accesibilidad web.
  • Código HTML más limpio y compacto.
  • No es necesario tener javascript habilitado.
  • Compatible con la totalidad de navegadores web.

Ejemplo validar formularios accesibles sin onsubmit

Descarga el ejemplo validar formularios accesibles sin onsubmit.

Para validar formularios web lo primero que debemos hacer es embeber el código javascript o cargarlo mediante un fichero externo entre las etiquetas head de nuestro código html:

<script type="text/javascript">
/**
 * Validar Formulario Accesible sin onSubmit
 * (c) 2009 Alejandro Arco
 * Por Alejandro Arco - https://alejandroarco.es
 */
validateForm=function() {
	var nombre = new Array(document.getElementById('nombre'), document.frm['nombre'].value);
	var apellidos = new Array(document.getElementById('apellidos'), document.frm['apellidos'].value);
	var email = new Array(document.getElementById('email'), document.frm['email'].value);
	var telefono = new Array(document.getElementById('telefono'), document.frm['telefono'].value);
	var consulta = new Array(document.getElementById('consulta'), document.frm['consulta'].value);	
	var submit = document.getElementById('submit');	
	
	/* Eventos */
	nombre[0].onfocus = onFocus; nombre[0].onblur = onBlur;
	apellidos[0].onfocus = onFocus; apellidos[0].onblur = onBlur;
	email[0].onfocus = onFocus; email[0].onblur = onBlur;
	telefono[0].onfocus = onFocus; telefono[0].onblur = onBlur;
	consulta[0].onfocus = onFocus; consulta[0].onblur = onBlur;	
	submit.onclick = validateFields;
	
	/* Funciones */
	function onFocus() { if(document.frm[this.name].value==eval(this.name)[1]) document.frm[this.name].value='' }	
	
	function onBlur() {
		var value = document.frm[this.name].value;
		value = value.replace(/^\s*/, ''); value = value.replace(/\s*$/, '');
		if(!value) document.frm[this.name].value = eval(this.name)[1]
	}
	
	function validateFields() {
		if(document.frm['nombre'].value == nombre[1]) { document.frm['nombre'].focus(); alert('El campo "nombre" es obligatorio.'); }
		else if(document.frm['apellidos'].value == apellidos[1]) { document.frm['apellidos'].focus(); alert('El campo "apellidos" es obligatorio.'); }
		else if(document.frm['email'].value == email[1]) { document.frm['email'].focus(); alert('El campo "email" es obligatorio.'); }
		else if(document.frm['consulta'].value == consulta[1]) { document.frm['consulta'].focus(); alert('El campo "consulta" es obligatorio.'); }
		else { return true; }
		return false;
	}
}

if(document.all&&window.attachEvent) { window.attachEvent("onload",validateForm); } // IE-Win
else if(window.addEventListener) { window.addEventListener("load",validateForm,false); } // Otros
</script>

Posteriormente, crearemos nuestro formulario web accesible y añadiremos su código entre las etiquetas body de nuestro contenido HTML.

  <form name="frm" action="#submit" enctype="multipart/form-data" method="post">
    <fieldset>
	  <legend>Formulario accesible</legend>
	  <p>Ejemplo de <strong>formulario accesible</strong> con <em>javascript</em> sin uso del atributo <em>onsubmit</em>, no olvide que todos los campos marcados con (*) son obligatorios.</p>
	  <label for="nombre">Nombre *</label><input name="nombre" id="nombre" accesskey="n" tabindex="1" value="- nombre -" type="text" />
	  <label for="apellidos">Apellidos *</label><input name="apellidos" id="apellidos" accesskey="a" tabindex="2" value="- apellidos -" type="text" />
	  <label for="email">Email *</label><input name="email" id="email" accesskey="e" tabindex="3" value="- email -" type="text" />
	  <label for="telefono">Teléfono</label> <input name="telefono" id="telefono" accesskey="t" tabindex="4" value="- teléfono -" type="text" />  
	  <label for="consulta">Consulta *</label><textarea name="consulta" id="consulta" accesskey="c" tabindex="5" cols="1" rows="1">- consulta -</textarea>  	  
	  <label for="submit"><input name="submit" id="submit" accesskey="s" tabindex="6" value="Enviar" type="submit" /></label>
	</fieldset>
  </form>

En este ejemplo no hacemos uso del atributo onsubmit para validar nuestro formulario web mediante javascript no intrusivo, de este modo, obtenemos un código html más limpio y compacto.

Si tenéis alguna duda referente a la validación de formularios web accesibles sin onsubmit, dejadme un comentario en este artículo y lo responderé gustosamente. ¿Habéis validado anteriormente formularios web con javascript no intrusivo?

Share

2 Comentarios

+ Añadir Comentario
  • Hola, muy buen aporte. Soy un tanto novato en php, y ni eso en javascript, mi pregunta es si desde el javascript puedo llamar a mi función en php para crear las Session.

    gracias, ALe

  • Hola y gracias por tu aporte, tengo una duda con este código para omitir la validación con onsubmit:

    function isValidDate(dateStr) {
    var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/; // año de 4 digitos
    var matchArray = dateStr.match(datePat); // revisa el formato?
    if (matchArray == null) {
     alert("La fecha ingresada no es correcta")
     return false;
    }
    month = matchArray[3]; // variables
     
    day = matchArray[1];
     
    year = matchArray[4];
     
    if (month  12) { // revisa el mes
     
    alert("El mes debe estar entre 1 y 12.");
     
    return false;
     
    }
     
    if (day  31) {
     
    alert("El día debe estar entre 1 y 31.");
     
    return false;
     
    }
     
    if ((month==4 || month==6 || month==9 || month==11) && day==31) {
     
    alert("Este mes no tiene 31 dias");
     
    return false;
     
    }
     
    if (month == 2) { // revisa si febrero tiene 29 dias
     
    var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
     
    if (day>29 || (day==29 && !isleap)) {
     
    alert("Febrero de " + year + " no tiene " + day + " dias!");
     
    return false;
     
       }
     
    }
     
    dateStr = month + "/" + day + "/" + year;
     
    return true;
     
    }
     
     
    
    function formatInput(dateStr){
     
    var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
     
    var matchArray = dateStr.match(datePat); 
     
    month = matchArray[3]; 
     
    day = matchArray[1];
     
    year = matchArray[4];
     
    return (month + "/" + day + "/" + year);
     
    }
     
    
     
    function dispDate(dateObj) {
     
    month = dateObj.getMonth()+1;
     
    month = (month < 10) ? "0" + month : month;
     
     
    day   = dateObj.getDate();
     
    day = (day < 10) ? "0" + day : day;
     
     
    year  = dateObj.getYear();
     
    if (year  0
     
     
     
    if (isValidDate(pregform.menstrual.value)) { // Validates menstual date 
     
    menstrualinput = new Date(formatInput(pregform.menstrual.value));
     
    menstrual.setTime(menstrualinput.getTime())
     
    }
     
    else return false; // otherwise exits
     
    cycle = (pregform.cycle.value == "" ? 28 : pregform.cycle.value); // defaults to 28
     
    // validates cycle range, from 22 to 45
     
    if (pregform.cycle.value != "" && (pregform.cycle.value  45)) {
     
    alert("Tu ciclo es demasiado corto o demasiado largo \n"
     
    + "para que el resultado sea preciso! Igualmente intentaremos \n"
     
    + "completar el calculo con los valores ingresados. ");
     
    }
     
    luteal = (pregform.luteal.value == "" ? 14 : pregform.luteal.value); // defaults to 14
     
    // validates luteal range, from 9 to 16
     
    if (pregform.luteal.value != "" && (pregform.luteal.value  16)) {
     
    alert("Tu fase lutea es demasiada corta o demasiada larga \n"
     
    + "para que el resuludo sea preciso! Igualmente intentaremos \n"
     
    + "completar el resultado con los valores ingresados. ");
     
    }
     
     
    // sets ovulation date to menstrual date + cycle days - luteal days
     
    // the '*86400000' is necessary because date objects track time
     
    // in milliseconds;  86400000 milliseconds equals one day
     
    ovulation.setTime(menstrual.getTime() + (cycle*86400000) - (luteal*86400000));
     
    pregform.conception.value = dispDate(ovulation);
     
     
    // sets due date to ovulation date plus 269 days
     
    
    // sets fetal age to 14 + 266 (pregnancy time) - time left
     
    return false; // form should never submit, returns false
     
    }
    

Si tienes alguna consulta, escríbela ...