Frage

So i am trying to create a Validator for a button which must check 3 textfields where one of them is a IP address. So basically the user has to enter the full IP address himself/herself.

So i have run into a unwanted syntax error, which i am sure is caused because of the textfield.

I tried converting the textfield into a string and then go through the validation but that just seems to make it worse

private class theValidator implements ActionListener{

    public void actionPerformed(ActionEvent e)
    {           
        String textIP = txfIP.getText();
        txfIP.setInputVerifier(new InputVerifier() {
            Pattern pat = Pattern.compile("\\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\."+
                    "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\." +
                    "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\." +
                    "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b");

            public boolean shouldYieldFocus(JComponent input) {
                boolean inputOK = verify(input);
                if (inputOK) {
                    return true;
                } 
                else {
                    Toolkit.getDefaultToolkit().beep();
                    return false;
                }
            }
            public boolean verify(JComponent input) {
                JTextField field = (JTextField) input;
                Matcher m = pat.matcher(field.getText());
                return m.matches();
            }
        });
}
}
War es hilfreich?

Lösung

1) I do not see a closing brace for txfIP.setInputVerifier(..

I'd recommend to use some editors like Eclipse to code, so that you will find it easy to catch errors like this.

2) As far as regex for validating ip address, you can try this. Hope that helps.

IPADDRESS_PATTERN = 
        "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
        "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
        "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
        "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";

Andere Tipps

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top