How to validate a field jTextField
with the format-pattern of a DNI
? Example: 72033197V
The pattern must have: 8 numbers + 1 letter (12345678A).
I have programmed the following code to validate a DNI
and it works. Is it the correct way of validation?
Test code:
import java.util.regex.*;
import java.util.Scanner;
public class validarDNI {
public static void main(String[] args) {
String dniIntroducido = null;
Scanner miScanner = new Scanner(System.in);
Pattern patron = Pattern.compile("[0-9]{7,8}[A-Z a-z]");
System.out.print("Introduce un DNI correcto: ");
dniIntroducido = miScanner.nextLine();
Matcher mat = patron.matcher(dniIntroducido);
while(!mat.matches()){
System.out.println("El DNI introducido es incorrecto, por favor introduzca un DNI válido.");
System.out.print("Introduce un DNI correcto: ");
dniIntroducido = miScanner.nextLine();
mat = patron.matcher(dniIntroducido);
}
System.out.println("El DNI " + dniIntroducido + " es válido.");
}
}
Well, my problem comes when importing it in a jTextField
to verify that it has 8 numbers and a single letter. And that when typing the letter it becomes uppercase ( toUpperCase()
).
He jTextField
is called: jTextField_DNI
.
I have created an event private void textfield_DNIKeyPressed(java.awt.event.KeyEvent evt) {
so that it checks character by character but... How do I implement it in the jTextField
?
private void textfield_DNIKeyPressed(java.awt.event.KeyEvent evt) {
}
The problem that you are going to have when checking character by character is that if you validate each time the user enters a character, the first 7 will result in
"DNI no válido"
even if everything is being written correctly. The most recommended thing is that you validate when itJTextField
loses focus, or when the user hits save, next, or any button to continue.To validate when it loses focus you add an
FocusListener
toJTextField
and implement the methodfocusLost
:Or if you want character by character then add a
KeyListener
toJTextField
and choose one of the 3 methods to implement the logic you want:With this method you validate if the letter is correct for the numeric part, as you know the module of the numeric part (8 digits) of 23, responds to a letter that corresponds to a Character of the string dniChars