如何验证EditText

时间:2013-06-24 12:27:48

标签: android

我正在创建一个显示记分板的应用程序,我想在此应用程序中进行验证。我想验证所有的Edittexts我该怎么做。 我想对EditText数组

执行验证
public class players extends Activity {
    LinearLayout player_layout;
    Bundle b;

    List<EditText> allEds = new ArrayList<EditText>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.players);

        b = getIntent().getExtras();
        String resStr = b.getString("name");

        player_layout = (LinearLayout) findViewById(R.id.player_layout);

        EditText[] ed1 = new EditText[Integer.parseInt(resStr)+1];
        Button add_player = new Button(players.this);
        add_player.setText("Add Players");

        for(int i=1;i<=Integer.parseInt(resStr);i++) {
            ed1[i] = new EditText(players.this);
            allEds.add(ed1[i]);
            player_layout.addView(ed1[i]);
            ed1[i].setId(i);
            ed1[i].setHint("enter player" +i+ "name");
            ed1[i].setHeight(50);
            ed1[i].setWidth(300);
        }

        LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        player_layout.addView(add_player, lp);

        add_player.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                Intent intent = new Intent(players.this,player_name.class);
                //Intent intent1 = new  Intent(players.this,player_name.class);
                String[] strings = new String[allEds.size()];

                for (int i=0; i < allEds.size(); i++){
                    strings[i] = allEds.get(i).getText().toString();
                    // intent.putExtra("playerName",b.getString("name"));
                    intent.putExtra("playerName",strings);
                }
                // intent1.putExtra("play",b.getString("name"));
                startActivity(intent);
                //startActivity(intent1);
            }
        });
    }
}

2 个答案:

答案 0 :(得分:0)

您可以编写正则表达式来验证输入字段。 示例代码

String Pattern = "[a-zA-Z]{5,31}";
if(textFromEditText.tostring().matches(Pattern)) {
//Valid
}

这是for string,你可以编写自己的正则表达式

答案 1 :(得分:0)

public void validation(){

for(int i=1;i<=Integer.parseInt(resStr);i++)
    {
        if(ed1[i].getText("").toString("").equals("")){
              Toast.makeText(youractivity.this, "Enter value in EditText"+i, Toast.LENGTH_SHORT).show();
                }

     }
   }