Exception handling for TextFields
Hey guys! This is my first post and its about an issue im having its driving me nuts and im sure its very simple yet i cannot figure it out! Here's the thing, i need to validate a textfield using Exceptions. Here are the validations:
- If the textfield contains a number, catch the exception and warn an error message
- If the text field contains an invalid character other than letters ( @#!?_, etc... ) , catch an exception and show an error message.
The other validations i pretty much managed to do them but those on the list i just cant seem to. I did manage to the opposite, which is "If the textfield contains a non-numeric character, catch the exception and show an error message". I did it like this:
Code :
try{
Integer.parseInt(jtextField.getText() );
}
catch ( NumberFormatException e ) {
JOptionPane.showMessageDialog(null, "The value must be a numeric value. " );
}
However i dont know how to do the opposite of that ( which is what i listed ). Any help please? :(
Thanks in advance.:o
Re: Exception handling for TextFields
First of all I would like to welcome to you to Java Prgoramming Forums. I hope we can help you out :)
Well here is an example that should get you thinking along the right lines and probably give you a solution. It's not using AWT or anything just commandline for ease. But you can implement it into your example easy enough.
Code :
public class FretDancer {
public void checkForInvalidCharacter(String s)
throws CustomFormatException {
for(int i = 0; i < s.length(); i++)
if(!Character.isLetterOrDigit(s.charAt(i)))
throw new CustomFormatException("Invalid Character");
}
public FretDancer(){
String testString = "Hello,";
try {
checkForInvalidCharacter(testString);
} catch (CustomFormatException cfe) { cfe.printStackTrace(); }
}
public static void main(String[] args) {
new FretDancer();
}
}
class CustomFormatException extends java.lang.Exception {
public CustomFormatException(String s){
super(s);
}
}
Just a note instead of using your own custom exception you could use IllegalArgumentException which would be used in the same way, but you wouldn't need the custom exception class.
Sorry for the slow reply.
Regards,
Chris