Friday, November 18, 2011

Formatting EditText input with regular expressions.

Source Code

Русский перевод.


It will be the short article. Now we will format text in EditText with regular expressions.

The simple class will extend Input Filter:

public class PartialRegexInputFilter implements InputFilter {
 
    private Pattern mPattern;
 
    public PartialRegexInputFilter(String pattern){
      mPattern = Pattern.compile(pattern);
    } 

    @Override
    public CharSequence filter(CharSequence source,
            int sourceStart, int sourceEnd,
            Spanned destination, int destinationStart,
            int destinationEnd) 
    {  
        String textToCheck = destination.subSequence(0, destinationStart).
            toString() + source.subSequence(sourceStart, sourceEnd) +
            destination.subSequence(
            destinationEnd, destination.length()).toString();
  
        Matcher matcher = mPattern.matcher(textToCheck);
  
        // Entered text does not match the pattern
        if(!matcher.matches()){
   
            // It does not match partially too
             if(!matcher.hitEnd()){
                 return "";
             }
   
        }
  
        return null;
    }

}


The trick is that if the input text does not match the pattern it can match it partially.
If so we will allow the text pasting.

And finally formatting a phone number:

final String regex = "\\(\\d{3}\\)\\d{3}\\-\\d{2}\\-\\d{2}";
        
txt.setFilters(
    new InputFilter[] {
        new PartialRegexInputFilter(regex)
    }
);
        
txt.addTextChangedListener(
    new TextWatcher(){

            @Override
            public void afterTextChanged(Editable s) {
                String value  = s.toString();
                if(value.matches(regex))
                    txt.setTextColor(Color.BLACK);
                else
                    txt.setTextColor(Color.RED);
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start,
                int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start,
               int before, int count) {}
           
         }
);
        



We have:




5 comments:

  1. This is awesome! Thanks so much. :-)

    ReplyDelete
  2. Just what I was looking for, thank you!

    ReplyDelete
  3. This is what I was looking for. However, you can improve by making symbols (dashes & brackets,..) put automatically when it's reached so the user can types only numbers

    ReplyDelete