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) {
}