EditText中的验证允许IP或Web Url主机

时间:2011-09-19 07:32:28

标签: android validation android-edittext

我需要对EditText进行验证,以便我可以输入有效的

IP地址格式(?。?。?。?),例如132.0.25.225

网址网址格式(www.?。?),例如www.example.com

逻辑是,如果用户首先键入任何数值,则验证(IP)将执行操作

否则用户必须在任何Web字符串

之前写“www”

注意:它必须执行EditText的 onKeyListener(),我的意思是当用户提供输入时

简而言之 - 我不打算检查用户何时完成输入并按OK按钮

任何想法都赞赏, 感谢。

6 个答案:

答案 0 :(得分:12)

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
}

答案 1 :(得分:1)

试试这个..

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


}

答案 2 :(得分:1)

这个离子对我来说非常适合检查android中的url

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

答案 3 :(得分:0)

EditText

中添加TextWatcher
afterTextChanged (Editable s)

使用正则表达式验证输入,如果输入字符与正则表达式不匹配,只需使用以下方法删除它。

Editable.delete(int start, int end)

答案 4 :(得分:0)

这是一个不同的IP地址验证解决方案,但也可用作网址验证的参考。

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;
}

}

答案 5 :(得分:0)

应该使用java.net.InetAddress类。您可以检查所有IP地址格式:主机地址(例如:132.0.25.225)或主机名(例如:www.google.com); IPv4或IPv6格式没问题。

源代码应该在工作线程上运行,因为有时InetAddress.getAllByName(mStringHost)需要很长时间。例如:您从主机名获取地址。

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()
相关问题