2

I have a simple EditText where a user can insert three values separated by commas. For instance, I can have the following template:

value1, value2, value3

where value1, value2 are of double type and value3 is integer.

How can I validate that the user has entered a text according to this template?

1 Answer 1

4

Use a regex Matcher.

final String DOUBLE = "\\d+(?:\\.\\d+)?";
final Pattern PATTERN = Pattern.compile(DOUBLE + ", " + DOUBLE + ", \\d+");
Matcher matcher = PATTERN.matcher(textView.getText().toString());
if (!matcher.matches()) {
    // invalid input
}
Sign up to request clarification or add additional context in comments.

5 Comments

Don't foreget to use the listener to catch the text changed event. [developer.android.com/reference/android/widget/…
I do not know why, but there should be added one correction: final String DOUBLE = "\\d+(?:\\.\\d+)?"; final Pattern Pattern = Pattern.compile(DOUBLE + ", " + DOUBLE + ", \\d+"); Can you correct and I'll accept the answer?
@Yury Silly me, you're right. In a java String literal, to get a black-slash, we need to escape it. So we need two back-slashes. Corrected my answer.
@Dheeraj Do not worry ) I think it was a nice training how I had understood the topic! Thanks!
@Yury To be more flexible, you can allow multiple spaces after the comma using , * for the separator. Also, leading & trailing spaces can be allowed by trimming the input: textView.getText().toString().trim().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.