Android EditText Validation and Regex

2019-07-29 11:29发布

问题:

i am about to create editText Validation for android, I used if..else statement but the coding seem like not working for my apps...I want to make all the field is mandatory,if you leave one field blank you cannot proceed, and I am also curious about the validation for phone number,since I am from Malaysia the valid phone number is eg:0133999504, the "-" symbol or any letter are disallowed..only digit and "+" sign are valid..Same goes for IC number, IC number in Malaysia is like a identity card number,I also want the "-" symbol disallowed only letter and digit are valid.. How to make the editText box border highlighted when the error occur?.. below is my full coding..is there any idea or solution?

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;

    }
}

回答1:

you can use this library for your validation.. A simple library for validating user input in forms using annotations.

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