安卓的EditText验证和正则表达式(Android EditText Validation an

2019-10-21 08:46发布

我将要创建EDITTEXT确认为Android,我用if..else语句但编码似乎不工作我的应用程序......我要让所有的领域是强制性的,如果你把一个领域的空白无法继续,而我也好奇了电话号码验证,因为我来自马来西亚是有效的电话号码例如:0133999504,在“ - ”符号或任何字母是disallowed..only数字,“+”号是valid..Same无二的身份证号码,在马来西亚的身份证号码就像是身份证号码,我也想了 - “”符号不允许只字母和数字是有效的。如何让错误发生时EDITTEXT框的边框突出..以下是我完全coding..is有任何想法或解决方案?

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;

    }
}

Answer 1:

你可以使用这个库为您的验证。一个简单的库验证使用注释形式的用户输入。

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



文章来源: Android EditText Validation and Regex