Azhar Shaikh Azhar Shaikh - 7 days ago 6
Android Question

Validation in EditText allow IP or web Url host

I am in need to give validation on my EditText such that it allows me to enter a valid

ip address format ( ?.?.?.? ) ie example 132.0.25.225

or

web url format ( www.?.? ) ie example www.example.com

logic is that if user type any numeric value first then validation(IP) will do action

else user must write "www" before any web String

Note: it must perform onKeyListener() of EditText, i mean while user giving input

In short - I am not going to check when user completes input and press OK button

Any idea appreciated,
Thanks.

Answer

ip

private static final String 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])$";

public static boolean validate(final String ip){          
      Pattern pattern = Pattern.compile(PATTERN);
      Matcher matcher = pattern.matcher(ip);
      return matcher.matches();             
}

url

try {
    new java.net.URI(url);
} catch(MalformedURLException e) {
    // url badly formed
}