Проверка Android EditText и регулярное выражение

1

Я собираюсь создать editText Validation для android, я использовал if..else, но кодирование, похоже, не работает для моих приложений... Я хочу, чтобы все поле было обязательным, если вы оставите одно поле пустым, вы не может продолжаться, и мне также интересно узнать о подтверждении номера телефона, так как я из Малайзии действительный номер телефона, например: 0133999504, символ "-" или любая буква запрещены... только цифры и знак "+" действительны.. То же самое касается номера IC, номер IC в Малайзии - это номер удостоверения личности, я также хочу, чтобы символ "-" был запрещен только буквой и цифрой. Как сделать рамку рамки editText выделенной, когда возникает ошибка?.. ниже - моя полная кодировка. Есть ли какая-нибудь идея или решение?

package com.sor.communityrideattendance;
import java.util.ArrayList;
import java.util.List;


import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.EditText;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.widget.Toast;
//import android.view.MenuInflater;
//import android.view.Menu;
import android.view.MenuItem; 

public class RiderProfile extends Activity {


    // Progress Dialog
    private ProgressDialog pDialog;


    JSONParser jsonParser = new JSONParser();
    EditText inputfullname;
    EditText inputIC;
    EditText inputmobileNo;
    EditText inputemergencyContactName;
    EditText inputemergencyContactNo;
    String PhoneNo;
    String PhoneNo_PATTERN ="^[+]?[0-9]{10,13}$";
    //private static final String TAG_ID = "ID";

    // url to create new product
    private static String url_create_rider = "http://192.168.0.28/android_connect/create_rider.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rider_profile);

        // Edit Text
        inputfullname= (EditText) findViewById(R.id.fullname);
        inputIC= (EditText) findViewById(R.id.IC);
        inputmobileNo= (EditText) findViewById(R.id.mobileNo);
        inputemergencyContactName= (EditText) findViewById(R.id.emergencyContactName);
        inputemergencyContactNo= (EditText) findViewById(R.id.emergencyContactNo);
        /*Create button*/
        Button btnSave = (Button) findViewById(R.id.btnSave);

        // button click event
        btnSave.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                // creating new product in background thread

                //start
                if(inputfullname.getText().toString().equals(""))
                {
                    inputfullname.setError("Please Enter Your Name");
                    Toast.makeText(RiderProfile.this, "Please filled in All field", Toast.LENGTH_SHORT).show();
                }
                else if(inputIC.getText().toString().equals("")) //IC
                    {
                    inputIC.setError("Please Enter Your IC Number");
                    Toast.makeText(RiderProfile.this, "Please filled in All field", Toast.LENGTH_SHORT).show();
                } else if(inputmobileNo.getText().toString().equals("")) //mobileNo
                {
                    Pattern pattern = Pattern.compile(PhoneNo_PATTERN);
                    Matcher matcher = pattern.matcher(PhoneNo);
                    if (!matcher.matches()) 
                    {
                    inputmobileNo.setError("Please Enter Your Mobile No");
                    }
                    else{
                    Toast.makeText(RiderProfile.this, "Please filled in All field", Toast.LENGTH_SHORT).show();
                    }
                }else if(inputemergencyContactName.getText().toString().equals("")) //emergencyName
                {
                    inputemergencyContactName.setError("Please enter Emergency Contact Name");  
                    Toast.makeText(RiderProfile.this, "Please filled in All field", Toast.LENGTH_SHORT).show();
                }else if(inputemergencyContactNo.getText().toString().equals("")) //emergencyNo
                {
                    Pattern pattern = Pattern.compile(PhoneNo_PATTERN);
                    Matcher matcher = pattern.matcher(PhoneNo);
                    if (!matcher.matches()) 
                    {
                    inputemergencyContactNo.setError("Please enter Emergency Contact No");
                    }
                    else{
                    Toast.makeText(RiderProfile.this, "Please filled in All field", Toast.LENGTH_SHORT).show();
                    }
                }
                //validation end
                else {
                new CreateNewRider().execute();
                }
            }
        });
    }

                //end



    /**
     * Background Async Task to Create new product
     * */
    class CreateNewRider extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(RiderProfile.this);
            pDialog.setMessage("Create Rider..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Creating rides
         * */
        protected String doInBackground(String... args) {
            String fullname= inputfullname.getText().toString();
            String IC= inputIC.getText().toString();
            String mobileNo= inputmobileNo.getText().toString();
            String emergencyContactName= inputemergencyContactName.getText().toString();
            String emergencyContactNo= inputemergencyContactNo.getText().toString();

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("fullname", fullname));
            params.add(new BasicNameValuePair("IC", IC));
            params.add(new BasicNameValuePair("mobileNo", mobileNo));
            params.add(new BasicNameValuePair("emergencyContactName", emergencyContactName));
            params.add(new BasicNameValuePair("emergencyContactNo", emergencyContactNo));

            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_create_rider,
                    "POST", params);

            // check log cat from response
            Log.d("Create Response", json.toString());

            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // successfully created product
                    Intent i = new Intent(getApplicationContext(), ListOfRider.class);
                    //Intent i = new Intent(getApplicationContext(), SuccessRidesProfile.class);
                    //in.putExtra(TAG_PID, pid);
                    startActivity(i);

                    // closing this screen
                    finish();
                } else {
                    // failed to create product
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            pDialog.dismiss();
        }

    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.items, menu);

        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        super.onOptionsItemSelected(item);
        final Context context = this;
        switch(item.getItemId()){
            case R.id.phone:

                Intent intent = new Intent(context, SubMenu.class);
                startActivity(intent);
                //Toast.makeText(getBaseContext(), "You selected Phone", Toast.LENGTH_SHORT).show();
                break;
        }

        return true;

    }
}
Теги:
validation
android-edittext

1 ответ

0
Лучший ответ

вы можете использовать эту библиотеку для проверки. Простая библиотека для проверки ввода пользователя в форме с использованием аннотаций.

https://github.com/inmite/android-validation-komensky

  • 0
    Главы вверх .. спасибо ..

Ещё вопросы

Сообщество Overcoder
Наверх
Меню