Java: Create Custom Regex JTextField

Posted on Updated on

When creating business (or really any other) application you always need to have some sort of input validation strategy. Usually the best practice is to start from the source, the user! If you allow the user to get invalid input past your program then it is your fault. For example a field that is only supposed to accept numbers should not allow the user to even be able to enter anything but numbers.

Normally in Java we like to use the JTextField class for input because it looks nice. We could use a JSpinner for number input, but sometimes it does not come out looking nice. So due to these issues I have developed the JCustomTextField with the following features:

  • Can set a maximum limit of characters
  • Input is validated by regular expressions
  • Input is validated at keypress

JCustomTextField Limited to 20 characters:

JCustomTextField field = new JCustomTextField();
field.setMaximumLength(20);


JCustomTextField Only Allow Numbers + Limit to 100 digits:

JCustomTextField field = new JCustomTextField();
field.setMaximumLength(100);
field.setRegexFilter("\\d+");

The Source Code

import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;

public class JCustomTextField extends JTextField {

	protected int maxLength = -1;
	//default regex, accept everything
	protected String regexCheck = ".*";
	protected boolean isBlocked = false;

	public JCustomTextField() {
		super();
	}

	public JCustomTextField(int cols) {
		super(cols);
	}
	
	public JCustomTextField(int cols, int maxLength) {
		super(cols);
		setMaximumLength(maxLength);
	}
	
	@Override
	protected Document createDefaultModel()
	{
		return new RegexDocument();
	}
	
	public int getMaximumLength()
	{
		return maxLength;
	}

	public void setMaximumLength(int max) {
		maxLength = max;
	}
	
	public String getRegexFilter()
	{
		return String.valueOf(regexCheck);
	}

	public void setRegexFilter(String regex) {
		regexCheck = regex;
	}

	public boolean isBlocked()
	{
		return isBlocked;
	}

	public void setBlocked(boolean bool) {
		isBlocked = bool;
	}

	private final class RegexDocument extends PlainDocument {
		@Override
		public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
			if(str == null) {
				return;
			}

			if(maxLength < 0) {
				if(str.matches(regexCheck)) {
					if (!isBlocked) {
						super.insertString(offs, str, a);
					}
					else {
						//send event
						//Max limit not reached
						//but invalid input
					}
				}
			}
			else {
				if(offs < maxLength && offs >= 0 
				   && str.matches(regexCheck)
				   && getLength() < maxLength) {
					if (!isBlocked) {
						super.insertString(offs, str, a);
					}
					else {
						//send event
						//Max limit reached
					}
				}
			}
		}
	}
}
Advertisements

One thought on “Java: Create Custom Regex JTextField

    Samuel LEMAITRE said:
    April 7, 2014 at 6:48 pm

    with this modification can read entire regex like a email regex not a complete example: “[a-z0-9]*(?:@[0-9a-z]*(?:\.[a-z]{0,6})?)?”

    @Override
    protected Document createDefaultModel()
    {
    return new RegexDocument(this);
    }

    and

    JTextField jtf;
    public RegexDocument(JTextField j)
    {
    jtf = j;
    }

    and finaly

    @Override
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
    if(str == null) {
    return;
    }
    String s = jtf.getText().substring(0,offs)+str+jtf.getText().substring(offs);
    if(maxLength < 0) {
    if(s.matches(regexCheck)) {
    if (!isBlocked) {
    super.insertString(offs, str, a);
    }
    else {
    //send event
    //Max limit not reached
    //but invalid input
    }
    }
    }
    else {
    if(s.length() <= maxLength && s.matches(regexCheck)) {
    if (!isBlocked) {
    super.insertString(offs, str, a);
    }
    else {
    //send event
    //Max limit reached
    }
    }
    }
    }

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s