Awais Zafar
Awais Zafar

Reputation: 53

How to validate EditText not to accept less than Maximum length values in android studio

I'm new to android. I want EditText shouldn't less than 10 digits in PhoneNumber as well as CNIC should also accept 13 digits.

Here's my code for project.

public class MainActivity extends AppCompatActivity implements OnClickListener{

Button btnSUB;
EditText et1,et2,et3,et4;
String validemail="[a-zA-Z0-9\\+\\.\\_\\%\\-]{1,256}" +"\\@" +"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +"(" +"\\." +"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +")+";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btnSUB = (Button) findViewById(R.id.buttonSubmit);
    et1 = (EditText) findViewById(R.id.editTextEmail);
    et2 = (EditText) findViewById(R.id.editTextName);
    et3 = (EditText) findViewById(R.id.editTextPhoneNumber);
    et4 = (EditText) findViewById(R.id.editTextCnic);
    btnSUB.setOnClickListener(this);
}


@Override
public void onClick(View view){

    String email=et1.getText().toString();
    Matcher matcher=Pattern.compile(validemail).matcher(email);
    if(matcher.matches()){
      Toast.makeText(getApplicationContext(),"Success...",Toast.LENGTH_LONG).show();


      Intent intent=new Intent(this,Main2Activity.class);

        intent.putExtra("Uname",et2.getText().toString());
        intent.putExtra("Uemail",et1.getText().toString());
        intent.putExtra("Uphone",et3.getText().toString());
        intent.putExtra("Ucnic",et4.getText().toString());
        startActivity(intent);
    }
    else{
        Toast.makeText(getApplicationContext(),"Enter a valid email!",Toast.LENGTH_LONG).show();
    }

}

}

Thank you in advance.

Upvotes: 2

Views: 539

Answers (3)

user3876059
user3876059

Reputation: 90

try this, in xml

<EditText
        android:id="@+id/edittext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:maxLength="10" />

And in java class make some validation like:

String value=edittext.getText().toString().trim();
    if (value.length()<10) {
        // show error message here
    }else{
        //number is valid
    }

Upvotes: 1

SpiritCrusher
SpiritCrusher

Reputation: 21063

Just check the length on proceed.

  String number=edittext.getText().toString().trim();
    if (number.length()<10) {
        edittext.setError("enter valid number");
    }else{
        //number is valid
    }

If you have a max limit too then set it in xml like below.

<EditText
    android:id="@+id/et_number"
    android:layout_width="fill_parent"
    android:maxLength="13"
    android:layout_height="wrap_content"
    />

Upvotes: 0

Samir Bhatt
Samir Bhatt

Reputation: 3261

You can check length of chars in Edittext while submit. e.g.

 if (edittext.getText().toString().trim().length() > 10) {
    // go ahead
  }else{
    // give error message  
  }

Upvotes: 0

Related Questions