acer
acer

Reputation: 303

How to validate to enter only decimal numbers or whole numbers,but not the symbols alone.(android)

I need to validate my edit text, I google it and find some links,but still couldn't get what I really want.

I need to validate the edit text input in android to allow decimal numbers,whole numbers and positive numbers,It won't allow only the characters (.,/,$) and spaces.

 <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:ems="10"
  />

I tried like this,but couldn't enter decimal number also.

I refer this link also http://developer.android.com/reference/java/util/regex/Pattern.html, still couldn't do.

Upvotes: 1

Views: 1388

Answers (2)

user3956566
user3956566

Reputation:

You could do something like this, controlling the min and max input chars and limiting it to a decimal value.

In your xml:

<EditText
    .../
    android:inputType="numberDecimal"
    android:maxLength="12"/>

Then in your java, validate the length, you could also validate range, but would need to parse the edittext value.
To test for a value that cannot only contain a fullstop and ask for a min input.

if(editText.getText().length()<2)
// throw error.

Also there is these two question and answers:

Limit Decimal Places in Android EditText

Getting decimal number from edittext

Upvotes: 1

Fabian Damken
Fabian Damken

Reputation: 1517

I do not know if it is possible in your scenario to validate the text against a regular expression, but you could use this expression to validate it:

^\d+(\.\d+)?$

It will allow full numbers (like 1234) and decimal number (like 1234.5678) but not something like 1234., .5678 or just a dot (or any other symbol).

Upvotes: 4

Related Questions