Foros del Web » Programación para mayores de 30 ;) » Java »

Validar RUT (Rol Único Tributario) en textfield Java

Estas en el tema de Validar RUT (Rol Único Tributario) en textfield Java en el foro de Java en Foros del Web. Comunidad: Tengo una aplicación de escritorio en Netbeans, la cual tiene 3 campos: RUT, nombre y apellido. Ya tengo validado para que me ingresen solamente ...
  #1 (permalink)  
Antiguo 25/10/2011, 08:05
 
Fecha de Ingreso: septiembre-2011
Mensajes: 40
Antigüedad: 12 años, 7 meses
Puntos: 0
Pregunta Validar RUT (Rol Único Tributario) en textfield Java

Comunidad:


Tengo una aplicación de escritorio en Netbeans, la cual tiene 3 campos: RUT, nombre y apellido.

Ya tengo validado para que me ingresen solamente números y el largo total de 10 dígitos.

Necesito hacer alguna validación, creo, por el lado del txtRUT para que me ingresen los RUT válidos.

Cualquier ayuda, por favor, me responden.

Lo otro: le puse el largo máximo de los textfield (nombre:30 y apellido 20), necesito
que los campos no me queden vacíos.

Dejo acá la excepción hecha del apellido:



package excepciones;

import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class ExcepcionApellido extends PlainDocument {

private JTextField miJTextField;
private int nroMaxCaracteres;

public ExcepcionApellido(JTextField mijtext, int nroMaxCaract)
{
miJTextField=mijtext;
nroMaxCaracteres=nroMaxCaract;
}

@Override
public void insertString(int arg0, String arg1, AttributeSet arg2) throws BadLocationException
{
for (int i=0;i<arg1.length();i++)
if ((!Character.isLetter(arg1.charAt(i)) && !Character.isSpaceChar(arg1.charAt(i)))||(miJTextF ield.getText().length()+arg1.length())>nroMaxCarac teres)
return;
super.insertString(arg0, arg1, arg2);
}
}
  #2 (permalink)  
Antiguo 30/11/2011, 12:50
 
Fecha de Ingreso: septiembre-2011
Mensajes: 40
Antigüedad: 12 años, 7 meses
Puntos: 0
Respuesta: Validar RUT (Rol Único Tributario) en textfield Java

Ayudaaaaaaaaaaaaa!!!!!!!!!!!!!
  #3 (permalink)  
Antiguo 01/12/2011, 07:37
Avatar de DeeR  
Fecha de Ingreso: diciembre-2003
Ubicación: Santiago
Mensajes: 520
Antigüedad: 20 años, 4 meses
Puntos: 17
Respuesta: Validar RUT (Rol Único Tributario) en textfield Java

En la red hay varios apuntes como validar un RUT

http://es.wikipedia.org/wiki/Rol_%C3%9Anico_Tributario (Información sobre el algortimo)
http://www.creations.cl/2009/01/gene...t-y-validador/ (Implementación en Java)

De todas formas, te dejo un ejemplo de como validar el RUT en un JTextfield

http://deerme.org/java/validacion-de-rut-en-java
Código Javascript:
Ver original
  1. package org.deerme.examples;
  2.  
  3. import java.awt.FlowLayout;
  4. import java.awt.event.ActionEvent;
  5. import java.awt.event.ActionListener;
  6. import javax.swing.JButton;
  7. import javax.swing.JFrame;
  8. import javax.swing.JLabel;
  9. import javax.swing.JOptionPane;
  10. import javax.swing.JTextField;
  11.  
  12. /**
  13.  * This is an example RUT validation
  14.  * @author deerme.org
  15.  */
  16. public class ValidarRut   extends JFrame implements ActionListener {
  17.  
  18.     private JButton btnValidar;
  19.     private JTextField txtRut;
  20.     private JLabel labRut;
  21.  
  22.     public ValidarRut()
  23.     {
  24.         super ( "Ejemplo de Validación de RUT" );
  25.         this.setSize(300, 300);
  26.         this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);        
  27.        
  28.         // Agregamos elementos a la ventana
  29.         this.setLayout( new FlowLayout(FlowLayout.LEFT, 20, 10)  );
  30.  
  31.         labRut = new JLabel("Rut");
  32.         txtRut = new JTextField(20);
  33.         txtRut.setText("16327531-7");
  34.         btnValidar = new JButton("Validar");
  35.         btnValidar.addActionListener(this);
  36.         this.add(labRut);
  37.         this.add(txtRut);
  38.         this.add(btnValidar);
  39.  
  40.         this.setVisible(true);
  41.        
  42.     }
  43.  
  44.  
  45.     public static void main(String[] args) {
  46.         // TODO code application logic here
  47.         new ValidarRut();
  48.     }
  49.  
  50.     public void actionPerformed(ActionEvent e) {
  51.  
  52.         // Validamos el RUt
  53.         if (e.getSource()==btnValidar)
  54.         {
  55.             if ( txtRut.getText().length() > 0  )
  56.             {
  57.                 // Creamos un arreglo con el rut y el digito verificador
  58.                 String[] rut_dv = txtRut.getText().split("-");
  59.                 // Las partes del rut (numero y dv) deben tener una longitud positiva
  60.                 if ( rut_dv.length == 2   )
  61.                 {
  62.                     // Capturamos error (al convertir un string a entero)
  63.                     try
  64.                     {
  65.                         int rut = Integer.parseInt( rut_dv[0] );
  66.                         char dv = rut_dv[1].charAt(0);
  67.  
  68.                         // Validamos que sea un rut valido según la norma
  69.                         if ( this.ValidarRut(rut, dv)  )
  70.                         {
  71.                             JOptionPane.showMessageDialog(rootPane, "Rut correcto");
  72.                         }
  73.                         else
  74.                         {
  75.                             JOptionPane.showMessageDialog(rootPane, "Rut incorrecto");
  76.                         }
  77.                     }
  78.                     catch( Exception ex )
  79.                     {
  80.                         System.out.println(" Error " + ex.getMessage());
  81.                     }
  82.                 }
  83.             }
  84.         }
  85.     }
  86.  
  87.     /*
  88.      * Método Estático que valida si un rut es válido
  89.      * Fuente : http://www.creations.cl/2009/01/generador-de-rut-y-validador/
  90.      */
  91.     public static boolean ValidarRut(int rut, char dv)
  92.     {
  93.         int m = 0, s = 1;
  94.         for (; rut != 0; rut /= 10)
  95.         {
  96.             s = (s + rut % 10 * (9 - m++ % 6)) % 11;
  97.         }
  98.         return dv == (char) (s != 0 ? s + 47 : 75);
  99.     }
  100.    
  101.  
  102. }

Última edición por DeeR; 01/12/2011 a las 07:38 Razón: :P

Etiquetas: netbeans, rut, textfield
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 11:19.