2011-09-19 8 views
6

ho bisogno di dare la convalida sul mio EditText tale che mi permette di entrare in unconvalida in EditText consentire esempio IP o web URL host

formato indirizzo IP valido (?.?.?.?) Vale a dire 132.0.25.225

o

formato uRL web (www.?.?) cioè esempio www.example.com

logica è che se l'utente digita qualsiasi valore numerico prima poi convalida (IP) farà azione

altro utente deve scrivere "www" prima di qualsiasi stringa web

Nota: si deve eseguire onKeyListener() di EditText, intendo mentre l'utente dando ingresso

In breve - Non ho intenzione di controllare quando l'utente completa l'input e premere il pulsante OK

Qualsiasi idea apprezzata, Grazie.

risposta

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 
} 
+0

la tua bella risposta. risolve la mia validazione IP, ma new java.net.URI (url); che verifica che il formato dell'indirizzo web non funzioni di conseguenza –

+1

UrlValidator urlValidator = new UrlValidator(); urlValidator.isValid ("http://asd.com"); http://commons.apache.org/validator/ – lacas

+0

non fa esattamente quello che voglio, ma aiuta. –

1

provare questo ..

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 


} 
+0

scusa funzionerà come (1.2.3.4) solo una cifra, a volte –

0

Aggiungi un TextWatcher al EditText e nel

afterTextChanged (Editable s) 

Convalidare l'input utilizzando un'espressione regolare e se il carattere di input non corrisponde alla regex, è sufficiente eliminarlo utilizzando il metodo seguente.

Editable.delete(int start, int end) 
1

Questo ione funziona perfettamente per me per la verifica URL in Android

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

Ecco una soluzione diversa per una validazione indirizzo IP, ma che potrebbe essere utilizzato come riferimento anche per una validazione web url.

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

}

0

dovrebbe utilizzare la classe java.net.InetAddress. puoi controllare tutti i moduli di indirizzo IP: indirizzo host (es .: 132.0.25.225) o nome host (ad esempio: www.google.com); Il formato IPv4 o IPv6 è ok.

Il codice sorgente deve essere eseguito sul thread di lavoro, poiché talvolta InetAddress.getAllByName (mStringHost) richiede molto tempo. ad esempio: ottieni l'indirizzo dal nome host.

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()