Foros del Web » Programando para Internet » Javascript »

Validacion de campos

Estas en el tema de Validacion de campos en el foro de Javascript en Foros del Web. Hola amigos tengo 4 botones de opcion(radio) Lo que quiero es que el usuario tenga que elegir alguna de las opciones por obligación, Si no ...
  #1 (permalink)  
Antiguo 19/11/2008, 13:39
Avatar de hardy2  
Fecha de Ingreso: noviembre-2007
Mensajes: 129
Antigüedad: 16 años, 5 meses
Puntos: 0
Validacion de campos

Hola amigos tengo 4 botones de opcion(radio)

Lo que quiero es que el usuario tenga que elegir alguna de las opciones por obligación,
Si no elije nada que salga un alert, y si elije una de las opciones , no deje seleccionar mas.

Tengo algo asi
if(jsfrm.pregunta[0].checked == false && jsfrm.pregunta[1].checked== false && jsfrm.pregunta[2].checked==false && jsfrm.pregunta[3].checked == false){
alert('elija una de las opciones');
f.opcion[0].focus();
return false;
}

no me funciona

gracias por su ayuda
  #2 (permalink)  
Antiguo 19/11/2008, 13:48
Avatar de JavierB
Colaborador
 
Fecha de Ingreso: febrero-2002
Ubicación: Madrid
Mensajes: 25.052
Antigüedad: 22 años, 2 meses
Puntos: 772
Respuesta: Validacion de campos

Hola hardy2

A ver si te sirve esto:

Código javascript:
Ver original
  1. for (i=0; ele=document.jsfrm.pregunta[i]; i++)
  2.   if (ele.checked) return
  3. alert('Error'),
  4. return false;

Saludos,
  #3 (permalink)  
Antiguo 19/11/2008, 14:06
Avatar de hardy2  
Fecha de Ingreso: noviembre-2007
Mensajes: 129
Antigüedad: 16 años, 5 meses
Puntos: 0
Respuesta: Validacion de campos

hola, gracias por responderme.
pero no me funciono..
a demas los otros campos de validacion, tampoco me funcionaron...
de todas maneras , gracias por tu ayuda..
Cita:
Iniciado por JavierB Ver Mensaje
Hola hardy2

A ver si te sirve esto:

Código javascript:
Ver original
  1. for (i=0; ele=document.jsfrm.pregunta[i]; i++)
  2.   if (ele.checked) return
  3. alert('Error'),
  4. return false;

Saludos,
  #4 (permalink)  
Antiguo 19/11/2008, 14:17
Avatar de David
Moderador
 
Fecha de Ingreso: abril-2005
Ubicación: In this planet
Mensajes: 15.720
Antigüedad: 19 años
Puntos: 839
Pregunta Respuesta: Validacion de campos

¿Cómo trataste de implementar el código?. Además, ¿cuál es el código HTML que estás usando?. ¿Has revisado la Consola de Errores de tu navegador?.
__________________
Por favor, antes de preguntar, revisa la Guía para realizar preguntas.
  #5 (permalink)  
Antiguo 19/11/2008, 14:28
Avatar de hardy2  
Fecha de Ingreso: noviembre-2007
Mensajes: 129
Antigüedad: 16 años, 5 meses
Puntos: 0
Respuesta: Validacion de campos

gracias por responder..

miara el codigo que estoy utilizando es el siguiente
Código HTML:
<html>

<head>
<title></title>




<script type="text/javascript">
<!--



function MM_validateForm() { //v4.0
  if (document.getElementById){
    var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
    for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]);
      if (val) { nm=val.name; if ((val=val.value)!="") {
        if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
          if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
        } else if (test!='R') { num = parseFloat(val);
          if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
          if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
            min=test.substring(8,p); max=test.substring(p+1);
            if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
      } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
    } if (errors) alert('The following error(s) occurred:\n'+errors);
    document.MM_returnValue = (errors == '');
} }
//-->
</script>
<script src="Scripts/AC_RunActiveContent.js" type="text/javascript"></script>

<script language="JavaScript">
<!-- Hide from old browsers


  var timerID = null
  var timerRunning = false
  function MakeArray(size) 
  {
  this.length = size;
  for(var i = 1; i <= size; i++)
  {
  this[i] = "";
  }
  return this;
  }
  function stopclock (){
  if(timerRunning)
  clearTimeout(timerID);
  timerRunning = false
  }
  function showtime () {
  var now = new Date();
  var year = now.getYear();
  var month = now.getMonth() + 1;
  var date = now.getDate();
  var hours = now.getHours();
  var minutes = now.getMinutes();
  var seconds = now.getSeconds();
  var day = now.getDay();
  Day = new MakeArray(7);
  Day[0]="Dom";
  Day[1]="Lun";
  Day[2]="Mar";
  Day[3]="Mié";
  Day[4]="Jue";
  Day[5]="Vie";
  Day[6]="Sáb";
  var timeValue = "";
  /*timeValue += (Day[day]) + "   ";
  */
  timeValue += ((month > 10) ? " " : " ") + month + "-";
  timeValue += date + "-" + year + "    ";
  timeValue += ((hours <= 12) ? hours : hours - 12);
  timeValue += ((minutes < 10) ? ":0" : ":") + minutes;
  timeValue += ((seconds < 10) ? ":0" : ":") + seconds;
  timeValue += (hours < 12) ? " AM" : " PM";
  document.jsfrm.face.value = timeValue;
  timerID = setTimeout("showtime()",1000);
  timerRunning = true
  }
  function startclock () {
  stopclock();
  showtime()
  }
  // End Hiding -->


</SCRIPT>

<script language="javascript">

function comprobar()
   {
      
   if(document.jsfrm.Nombre.value=='')
     {
	 alert ('- Debe introducir el nombre')
	 return(1)
	 }
	
	if(document.jsfrm.Correo.value=='') 
		{
	 alert ('- Debe ingresar su correo')
	 return(1)
	 }
	 
	 if(document.jsfrm.Cedula.value=='')
     {
	 alert ('- Escoja una de las opciones')
	 return(1)

if (document.jsfrm.opcion[a].checked == false && document.jsfrm.opcion[b].checked == false) {
alert("Debes seleccionar una de las dos opciones!.");
f.opcion[0].focus();
return false;
}

	 }
	 }
	 
</script>



</head>


<body onLoad="startclock();">
<FORM NAME='jsfrm' method="post" action="Almacenar.asp" onSubmit="if (comprobar()) return(false)">
<table width="607" height="207" border="1" align="center" cellpadding="3" bordercolor="#993366">
  <tr bgcolor="#000000">
    <td height="5" colspan="3" align="center" valign="middle" bgcolor="#FFFFFF">&nbsp;</td>
  </tr>
  <tr bgcolor="#000000">
    <td height="6" colspan="3" align="center" valign="middle" bgcolor="#FFFFFF">
      
        <div align="right">
          <input type=text name='face' size=22 value=''>
        </div></td>
    </tr>
  <tr bgcolor="#000000">
    <td height="5" colspan="3" align="center" valign="middle" bgcolor="#993366"><div align="center"><font color="#FFFFFF" size="2" face="Verdana, Arial, Helvetica, sans-serif">Datos personales</font></div>
    <div align="left"></div></td>
    </tr>
  <tr>
    <td width="183" height="28" align="center" valign="middle"><p align="left"><font face="Verdana, Arial, Helvetica, sans-serif" size="2"> Nombre Completo:</font> </p></td>
    <td colspan="2" align="left" valign="middle"><font face="Verdana, Arial, Helvetica, sans-serif" size="2">
      <input name="Nombre" type="text" id="Nombre" size="50" maxlength="100" />
    </font></td>
  </tr>
  <tr>
    <td height="28" align="left" valign="middle"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">E-mail:<br>
    </font></td>
    <td height="28" colspan="2" align="left" valign="middle"><input name="Correo" type="text" id="Correo" size="50" maxlength="50"></td>
  </tr>
  <tr>
    <td height="16" colspan="3" align="left" valign="middle" bgcolor="#993366">
      <font size="2">
      <label> </label>
      </font>
      <div align="center"><font color="#FFFFFF" size="2" face="Verdana, Arial, Helvetica, sans-serif">Respuesta</font></div>
      </td>
    </tr>
  <tr>
    <td height="17" colspan="3" align="left" valign="middle"><table width="559" border="0" align="center">
      <tr>
        <td width="148"><label>
          <strong>a-</strong>121.100
          <input type="radio" name="pregunta" id="radio" value="a">
        </label></td>
        <td width="127"><strong>b-</strong>130.584
          <label>
          <input type="radio" name="pregunta" id="radio2" value="b">
          </label></td>
        <td width="133"><strong>c-</strong> 120.298  
          <label>
          <input type="radio" name="pregunta" id="radio3" value="c">
          </label></td>
        <td width="123"><strong>d-</strong> 127.358
          <label>
          <input type="radio" name="pregunta" id="radio4" value="d">
          </label></td>
      </tr>
    </table></td>
    </tr>
  <tr>
    <td height="47" colspan="3" align="center" valign="middle"><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><span style="word-spacing: 0; margin-right: 0; margin-top: 0; margin-bottom: 0">
      <input name="submit_button" type="submit" onClick="MM_validateForm('Correo','','NisEmail');return document.MM_returnValue" value="Enviar" />
      <input type="reset" value="Limpiar formulario" name="B2" />
    </span></font></td>
  </tr>
</table>
<p align="center">&nbsp;</p>
<p align="center">&nbsp;</p>
</FORM>

</body>

</html> 
es un pequeño formulario pero no me funcionan los botones de radio,,..debe salir en un alert " debe seleccionar una de loas opciones"

gracias por tu ayuda
Cita:
Iniciado por David el Grande Ver Mensaje
¿Cómo trataste de implementar el código?. Además, ¿cuál es el código HTML que estás usando?. ¿Has revisado la Consola de Errores de tu navegador?.
  #6 (permalink)  
Antiguo 19/11/2008, 14:32
Avatar de David
Moderador
 
Fecha de Ingreso: abril-2005
Ubicación: In this planet
Mensajes: 15.720
Antigüedad: 19 años
Puntos: 839
Respuesta: Validacion de campos

Pero, no implementaste el código de JavierB. Además, estás retornando false (return false) cuando en el contexto de tu función y validación deberías retornar true cuando ninguno de los radio están seleccionados.
__________________
Por favor, antes de preguntar, revisa la Guía para realizar preguntas.
  #7 (permalink)  
Antiguo 19/11/2008, 14:40
Avatar de hardy2  
Fecha de Ingreso: noviembre-2007
Mensajes: 129
Antigüedad: 16 años, 5 meses
Puntos: 0
Respuesta: Validacion de campos

aqui tengo implementado el codigo de javier... pero no me funciona nada..
Código:
function comprobar()
   {
      
   if(document.jsfrm.Nombre.value=='')
     {
	 alert ('- Debe introducir el nombre')
	 return(1)
	 }
	
	if(document.jsfrm.Correo.value=='') 
		{
	 alert ('- Debe ingresar su correo')
	 return(1)
	 }
	 
	 if(document.jsfrm.Cedula.value=='')
     {
	 alert ('- Escoja una de las opciones')
	 return(1)

for (i=0; ele=document.jsfrm.pregunta[i]; i++)  
if (ele.checked) retur
nalert('Error'),
return false;
	 }
	 
</script>
Cita:
Iniciado por David el Grande Ver Mensaje
Pero, no implementaste el código de JavierB. Además, estás retornando false (return false) cuando en el contexto de tu función y validación deberías retornar true cuando ninguno de los radio están seleccionados.
  #8 (permalink)  
Antiguo 19/11/2008, 14:46
Avatar de David
Moderador
 
Fecha de Ingreso: abril-2005
Ubicación: In this planet
Mensajes: 15.720
Antigüedad: 19 años
Puntos: 839
Respuesta: Validacion de campos

Error de "ortografía" de JavierB . Puso , en lugar de ;, además, como te había dicho, en el contexto de tu función debes devolver false cuando es correcto, y true cuando es incorrecto . O sea:
Código javascript:
Ver original
  1. for (i=0; ele=document.jsfrm.pregunta[i]; i++)  
  2.    if (ele.checked) return false;
  3. alert('Error');
  4. return true;
__________________
Por favor, antes de preguntar, revisa la Guía para realizar preguntas.
  #9 (permalink)  
Antiguo 19/11/2008, 14:58
Avatar de hardy2  
Fecha de Ingreso: noviembre-2007
Mensajes: 129
Antigüedad: 16 años, 5 meses
Puntos: 0
Respuesta: Validacion de campos

jeje..ok muchas gracias por tu ayuda..

Cita:
Iniciado por David el Grande Ver Mensaje
Error de "ortografía" de JavierB . Puso , en lugar de ;, además, como te había dicho, en el contexto de tu función debes devolver false cuando es correcto, y true cuando es incorrecto . O sea:
Código javascript:
Ver original
  1. for (i=0; ele=document.jsfrm.pregunta[i]; i++)  
  2.    if (ele.checked) return false;
  3. alert('Error');
  4. return true;
  #10 (permalink)  
Antiguo 19/11/2008, 15:05
Avatar de JavierB
Colaborador
 
Fecha de Ingreso: febrero-2002
Ubicación: Madrid
Mensajes: 25.052
Antigüedad: 22 años, 2 meses
Puntos: 772
Respuesta: Validacion de campos

Oops, perdón por el error de dedo. Menos mal que David ha estado atento.

Saludos,
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 14:04.