Friday, August 7, 2015

JavaFx - Validating Text Field with IP

Recently, I happen to come across IP validation problem in JavaFX code. So, I googled and googled. In the end, I found the relevant information. Here are some lines of codes, which is useful. Use it when you need it.

1. @FXML
    private TextField ip;

2.  if (!validateIP(ip.getText())) {
                showDialog("Invalid IP Address");
            }

3.  public boolean validateIP(final String ip) {
        Pattern pattern;
        Matcher matcher;
        String 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])$";
        pattern = Pattern.compile(IPADDRESS_PATTERN);
        matcher = pattern.matcher(ip);
        return matcher.matches();
    }

1 comment: