Android EditText uses regular expressions for input filtering

Source: Internet
Author: User

Recently, the password modification function is used in a project. However, we do not want users to enter Chinese or special characters for Password Input. Therefore, we need to filter the input boxes of users, the following is a small code snippet for filtering EditText:

 

1. First, add a TextWatcher to Edittext. Of course, this TextWatcher must be written by ourselves. The core functions are also in this class.

 

[Java]
MOldPwdET. addTextChangedListener (new SearchWather (mOldPwdET ));

 

2. The following is the custom TextWatcher.

 

[Java]
Class SearchWather implements TextWatcher {
 
 
// Monitor the changed text box
Private EditText editText;
 
/**
* Constructor
*/
Public SearchWather (EditText editText ){
This. editText = editText;
}
 
@ Override
Public void onTextChanged (CharSequence ss, int start, int before, int count ){
String editable = editText. getText (). toString ();
String str = stringFilter (editable. toString ());
If (! Editable. equals (str )){
EditText. setText (str );
// Set the position of the new cursor www.2cto.com
EditText. setSelection (str. length ());
}
}
 
@ Override
Public void afterTextChanged (Editable s ){
 
}
@ Override
Public void beforeTextChanged (CharSequence s, int start, int count, int after ){
 
}
 
}
 
 
Public static String stringFilter (String str) throws PatternSyntaxException {
// Only letters and numbers are allowed
String regEx = "[^ a-zA-Z0-9]";
Pattern p = Pattern. compile (regEx );
Matcher m = p. matcher (str );
Return m. replaceAll (""). trim ();
}

 

I hope you can share with us any better solutions.

 


Author jamin0107

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.