Validation in EditText allow IP or web Url host

2019-04-10 00:17发布

问题:

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.

回答1:

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
}


回答2:

try this ..

public void checkIP(String Value)
{
    Pattern pattern = Pattern.compile("[0-255].[0-255].[0-255].[0-255]");
    Matcher matcher = pattern.matcher(Value);
    boolean IPcheck = matcher.matches();
    if(IPcheck)
           //it is IP
        else
           //it is not IP


}


回答3:

This ione works perfectly for me for checking url in android

 if (!URLUtil.isValidUrl(url)) {
    Toast.makeText(this, "Invalid URL", Toast.LENGTH_SHORT).show();
    return;
    }


回答4:

Add a TextWatcher to your EditText and in the

afterTextChanged (Editable s)

Validate the input using a regex and if the input character doesn't match the regex, simply delete it using the following method.

Editable.delete(int start, int end)


回答5:

Here a different solution for an IP address validation but that could be used as reference also for a web url validation.

EditText ipText = (EditText) findViewById(R.id.ip_address);
ipText.setKeyListener(IPAddressKeyListener.getInstance());

.........

public class IPAddressKeyListener extends NumberKeyListener {

private char[] mAccepted;
private static IPAddressKeyListener sInstance;

@Override
protected char[] getAcceptedChars() {
    return mAccepted;
}

/**
 * The characters that are used.
 * 
 * @see KeyEvent#getMatch
 * @see #getAcceptedChars
 */
private static final char[] CHARACTERS =

new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.' };

private IPAddressKeyListener() {
    mAccepted = CHARACTERS;
}

/**
 * Returns a IPAddressKeyListener that accepts the digits 0 through 9, plus
 * the dot character, subject to IP address rules: the first character has
 * to be a digit, and no more than 3 dots are allowed.
 */
public static IPAddressKeyListener getInstance() {
    if (sInstance != null)
        return sInstance;

    sInstance = new IPAddressKeyListener();
    return sInstance;
}

/**
 * Display a number-only soft keyboard.
 */
public int getInputType() {
    return InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL;
}

/**
 * Filter out unacceptable dot characters.
 */
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

    if (end > start) {
        String destTxt = dest.toString();
        String resultingTxt = destTxt.substring(0, dstart)
                + source.subSequence(start, end)
                + destTxt.substring(dend);
        if (!resultingTxt.matches("^\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3})?)?)?)?)?)?")) {
            return "";
        } else {
            String[] splits = resultingTxt.split("\\.");
            for (int i = 0; i < splits.length; i++) {
                if (Integer.valueOf(splits[i]) > 255) {
                    return "";
                }
            }
        }
    }
    return null;
}

}



回答6:

should use java.net.InetAddress class. you can check for all formarts of IP address: host address (eg: 132.0.25.225) or host name (eg: www.google.com); IPv4 or IPv6 format is ok.

Source code should run on work thread, because sometime InetAddress.getAllByName(mStringHost) take long time. for example: you get address from host name.

Thread mThread = new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            String mStringHost = "www.google.com";
            //String mStringHost = "192.168.1.2";
            InetAddress[] list_address = InetAddress.getAllByName(mStringHost);
            if(list_address != null && list_address.length >=1){
                InetAddress inetAddress = list_address[0];
                Log.d("test","inetAddress ="+ inetAddress.getHostAddress());
                if( inetAddress instanceof Inet4Address){
                    //IPv4 process
                }else{
                    //IPv6 process
                }
            }else{
                throw new Exception("invalid address");
            }
        }catch(Exception e){
            Log.e(TAG,"other exception",e);
            Toast.makeText(context, "Invalid host address or host name", Toast.LENGTH_SHORT).show();
            //process invalide ip address here
        }
    }
});

mThread.start()