I have to validate a series of TextField in a JavaFX application. I think the best way would be regular expressions. But I'm not hitting the nail on the head. I need to validate an input that does not contain more than 25 characters and does not contain special characters like @#$€%€/()=? etc. My code is the following:
@FXML
void handleMarca(KeyEvent event) {
String m = txtMarca.getText()+event.getCharacter();
if( m.length() > 25 || m.matches("[^ A-Za-z0-9]" )){
ClaseAccesoria.dialogo("Escriba un nombre inferior a 25 caracteres.\n +
"Solo se admiten letras y dígitos.", ERROR);
}else{
Marca = txtMarca.getText();
}
}//fin metodo
As I have written the regular expression it would say that it puts "reject any character that is not A-Za-z0-9" But for now it accepts them without problem. Could someone tell me how to make a regular expression that does not accept special characters, or only accepts special characters and deny it. And if I can include that it only admits less than 25 characters....
The java method
matches
makes the regular expression implicitly carry a beginning and ending string.So when you use the regular expression
really what you have is:
So you are simply detecting strings longer than 25 lengths or single character strings other than white or letters and numbers as problematic.
If you enter a single character in your field it should fail. Try
-
eg.To use
matches
and get it working for you, try changing the regular expression to the following:Another slightly more efficient version (in case the text was very long) would be:
But the most efficient and what makes the most sense is to simply look for correct (rather than incorrect) things and negate the match condition:
Where
equals
For use
matches
And therefore it means that the string must comply that from the beginning to the end it is made up of 0 or more (
*
) characters that can be a-ZA-Z0-9 and blank.By denying it, it is a way to find the rest of the cases that do not comply.