在android中验证血型和出生日期

时间:2016-05-04 05:22:45

标签: android

Hai我对android开发很新。我试图在我的申请中验证血型(AB + OR AB-或A + OR A-或B + OR B-或O + OR-)和出生数据(DD / MM / YYY)。如何编写代码以验证血型和出生日期。以下是我的代码;

Main activity:-

    package com.example.uniqval.registration;

    import android.content.ContentValues;
    import android.content.Intent;
    import android.database.sqlite.SQLiteDatabase;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    import android.text.Editable;
    import android.text.TextUtils;
    import android.text.TextWatcher;
    import android.view.View;
    import android.view.WindowManager;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;

    public class MainActivity  extends AppCompatActivity implements View.OnClickListener {

        private Button mSubmit;
        private Button mCancel;
        private EditText mname;
        private EditText dob;
        private EditText mUsername;
        private EditText mPassword;
        private EditText mEmail;
        private EditText mphone;
        private EditText maddress;
        private EditText mbloodgroup;
        private EditText memergencycontactno1;
        private EditText memergencycontactno2;

    //    private Spinner mGender;
    //    private String Gen;

        protected DBHelper DB = new DBHelper(MainActivity.this);

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);

    0
        }


        @Override
        protected void onResume() {
            super.onResume();

            mSubmit = (Button)findViewById(R.id.submit);
            mSubmit.setOnClickListener(this);

            mCancel = (Button)findViewById(R.id.cancel);
            mCancel.setOnClickListener(this);

            mname = (EditText)findViewById(R.id.efname);
            dob = (EditText)findViewById(R.id.dob);

            mUsername = (EditText)findViewById(R.id.reuname);
            mPassword = (EditText)findViewById(R.id.repass);
            mEmail = (EditText)findViewById(R.id.eemail);
            mphone=(EditText)findViewById(R.id.pphoneno);
            maddress=(EditText)findViewById(R.id.paddress);
            mbloodgroup=(EditText)findViewById(R.id.pbldgrp);
            memergencycontactno1=(EditText)findViewById(R.id.pemc1);
            memergencycontactno2=(EditText)findViewById(R.id.pemc2);

            //     mGender = (Spinner)findViewById(R.id.spinner1);

            // Spinner method to read the on selected value
          /*  ArrayAdapter<State> spinnerArrayAdapter = new ArrayAdapter<State>(this,
                    android.R.layout.simple_spinner_item, new State[] {
                    new State("Male"),
                    new State("Female")});
            mGender.setAdapter(spinnerArrayAdapter);
            mGender.setOnItemSelectedListener(this);*/
        }

        @Override
        public void onClick(View v) {

            switch (v.getId()) {

                case R.id.cancel:
                    Toast.makeText(getApplicationContext(), "registration cancelled", Toast.LENGTH_SHORT).show();
                    break;

                case R.id.submit:

                    if(!validateName())
                    {
                        return;
                    }
                    if(!validateDOB())
                    {
                        return;
                    }
                    if(!validateUserName())
                    {
                        return;
                    }
                    if(!validatePassword())
                    {
                        return;
                    }
                    if(!validateEmail())
                    {
                        return;
                    }
                    if(!validatePhoneNumber())
                    {
                        return;
                    }
                    if(!validateAddress())
                    {
                        return;
                    }
                    if(!validateBloodGr())
                    {
                        return;
                    }
                    if(!validateContact1())
                    {
                        return;
                    }
                    if(!validateContact2())
                    {
                        return;
                    }

                    addEntry(mname.getText().toString(), dob.getText().toString(), mUsername.getText().toString(), mPassword.getText().toString(),
                            mEmail.getText().toString(), mphone.getText().toString(),maddress.getText().toString(),mbloodgroup.getText().toString(),
                            memergencycontactno1.getText().toString(),memergencycontactno2.getText().toString());
                    Toast.makeText(getApplicationContext(), "registration sucess", Toast.LENGTH_SHORT).show();
                    finish();
                    //           String fname = mname.getText().toString();
                    /*String dofb = dob.getText().toString();

                    String uname = mUsername.getText().toString();
                    String pass = mPassword.getText().toString();
                    String email = mEmail.getText().toString();
                    String PhoneNo = mphone.getText().toString();
                    String Address=maddress.getText().toString();
                    String BloodGroup=mbloodgroup.getText().toString();
                    String EmergencyContactNo1=memergencycontactno1.getText().toString();
                    String EmergencyContactNo2=memergencycontactno2.getText().toString();
    */
                  /*  boolean invalid = false;

                    if (fname.equals("")) {
                        invalid = true;
                        Toast.makeText(getApplicationContext(), "Enter your Firstname", Toast.LENGTH_SHORT).show();
                    } else if (dofb.equals("")) {
                        invalid = true;
                        Toast.makeText(getApplicationContext(), "Please enter your Lastname", Toast.LENGTH_SHORT).show();
                    } else if (uname.equals("")) {
                        invalid = true;
                        Toast.makeText(getApplicationContext(), "Please enter your Username", Toast.LENGTH_SHORT).show();
                    } else if (pass.equals("")) {
                        invalid = true;
                        Toast.makeText(getApplicationContext(), "Please enter your Password", Toast.LENGTH_SHORT).show();

                    } else if (email.equals("")) {
                        invalid = true;
                        Toast.makeText(getApplicationContext(), "Please enter your Email ID", Toast.LENGTH_SHORT).show();
                    } else if (PhoneNo.equals("")) {
                        invalid = true;
                        Toast.makeText(getApplicationContext(), "Please enter your phone number", Toast.LENGTH_SHORT).show();

                    }
                    else if (Address.equals("")) {
                        invalid = true;
                        Toast.makeText(getApplicationContext(), "Please enter your Address", Toast.LENGTH_SHORT).show();
                    }
                    else if (BloodGroup.equals("")) {
                        invalid = true;
                        Toast.makeText(getApplicationContext(), "Please enter your BloodGroup", Toast.LENGTH_SHORT).show();
                    }
                    else if (EmergencyContactNo1.equals("")) {
                        invalid = true;
                        Toast.makeText(getApplicationContext(), "Please enter your EmergencyContactNo1", Toast.LENGTH_SHORT).show();
                    }
                    else if (EmergencyContactNo2.equals("")) {
                        invalid = true;
                        Toast.makeText(getApplicationContext(), "Please enter your EmergencyContactNo2", Toast.LENGTH_SHORT).show();
                    }
                    else if (invalid == false) {*/

                    //finish();
               /*     }

                    break;*/

            }

        }
        private boolean validateName() {
            if (mname.getText().toString().trim().isEmpty()) {
                try {
                    mname.setError("Enter Your Name");
                }
                catch (Exception e)
                {}
                requestFocus(mname);
                return false;
            }
            return true;
        }

        private boolean validateDOB() {
            if (dob.getText().toString().trim().isEmpty()) {
                try {
                    dob.setError("Enter Your Date of Birth");
                }
                catch (Exception e)
                {}
                requestFocus(dob);
                return false;
            }
            return true;
        }

        private boolean validateUserName() {
            if (mUsername.getText().toString().trim().isEmpty()) {
                try {
                    mUsername.setError("Enter User Name");
                }
                catch (Exception e)
                {}
                requestFocus(mUsername);
                return false;
            }
            return true;

    }

    private boolean validateAddress() {
        if (maddress.getText().toString().trim().isEmpty()) {
            try {
                maddress.setError("Enter Address");
            }
            catch (Exception e)
            {}
            requestFocus(maddress);
            return false;
        }
        return true;
    }

    private boolean validateContact1() {
        if (memergencycontactno1.getText().toString().trim().isEmpty()) {
            try {
                memergencycontactno1.setError("Enter Contact Number");
            }
            catch (Exception e)
            {}
            requestFocus(memergencycontactno1);
            return false;
        }
        return true;
    }

    private boolean validateContact2() {
        if (memergencycontactno2.getText().toString().trim().isEmpty()) {
            try {
                memergencycontactno2.setError("Enter Contact Number");
            }
            catch (Exception e)
            {}
            requestFocus(memergencycontactno2);
            return false;
        }
        return true;
    }

    private boolean validateBloodGr() {
        if (mbloodgroup.getText().toString().trim().isEmpty()) {
            try {
                mbloodgroup.setError("Enter Your Blood group");
            }
            catch (Exception e)
            {}
            requestFocus(mbloodgroup);
            return false;
        }
        return true;
    }
    private boolean validatePhoneNumber() {
        if (mphone.getText().toString().trim().isEmpty()) {
            try {
                mphone.setError("Enter Your phone number");
                if (mphone.length()!=10)
                    Toast.makeText(getApplicationContext(), "Please enter your valid 10 digit phone number", Toast.LENGTH_SHORT).show();

                }
            catch (Exception e)
            {}
            requestFocus(mphone);
            return false;
        }

            return true;
    }

    private boolean validatePassword() {
        if (mPassword.getText().toString().trim().isEmpty()) {
            try {
                mPassword.setError("Enter Your Password");
            } catch (Exception e) {
            }
            requestFocus(mPassword);
            return false;
        }

        return true;
    }

    private boolean validateEmail() {
        String email = mEmail.getText().toString().trim();
        if (email.isEmpty() || !isValidEmail(email)) {
            try {
                mEmail.setError("Invalid email id");
            }
            catch (Exception e)
            {}
            requestFocus(mEmail);
            return false;
        }

        return true;
    }
    private boolean validatergencycontactno1() {
        if (mphone.getText().toString().trim().isEmpty()) {
            try {
                memergencycontactno1.setError("Enter Your phone number");
                if (memergencycontactno1.length()!=10)
                    Toast.makeText(getApplicationContext(), "Please enter your valid 10 digit emergencycontactno1", Toast.LENGTH_SHORT).show();

            }
            catch (Exception e)
            {}
            requestFocus(mphone);
            return false;
        }

        return true;
    }
    private boolean validatebloodgroup(){

        return true;
    }
    private boolean validatergencycontactno2() {
        if (mphone.getText().toString().trim().isEmpty()) {
            try {
                memergencycontactno2.setError("Enter Your phone number");
                if (memergencycontactno2.length()!=10)
                    Toast.makeText(getApplicationContext(), "Please enter your valid 10 digit emergencycontactno2", Toast.LENGTH_SHORT).show();

            }
            catch (Exception e)
            {}
            requestFocus(mphone);
            return false;
        }

        return true;
    }

    private static boolean isValidEmail(String email) {
        return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
    }

    private void requestFocus(View view) {
        if (view.requestFocus()) {
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
    }


    public void onDestroy()
    {
        super.onDestroy();
        DB.close();
    }



    private void addEntry(String name, String dob, String uname, String pass, String email, String phoneno, String addr,
                          String bloodgr, String contact1, String contact2)
    {

        SQLiteDatabase db = DB.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put("name", name);
        values.put("dob", dob);
        values.put("username", uname);
        values.put("password", pass);
        values.put("email", email);
        values.put("phoneno", phoneno);
        values.put("address", addr);
        values.put("bloodgroup", bloodgr);
        values.put("econtact1", contact1);
        values.put("econtact2", contact2);

        try
        {
            db.insert(DBHelper.DATABASE_TABLE_NAME, null, values);

            Toast.makeText(getApplicationContext(), "your details submitted Successfully...", Toast.LENGTH_SHORT).show();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

content_main.xml:-
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_marginBottom="10dp" android:paddingTop="@dimen/activity_vertical_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingBottom="@dimen/activity_vertical_margin" android:layout_weight="2" android:layout_height="match_parent" android:layout_width="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.uniqval.registration.MainActivity"
    tools:showIn="@layout/activity_main">

    <LinearLayout
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:orientation="vertical">
        <LinearLayout
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:orientation="vertical">
            <android.support.design.widget.TextInputLayout
                android:layout_height="wrap_content"
                android:layout_width="match_parent"
                android:id="@+id/til"><EditText
                android:layout_height="wrap_content"
                android:layout_width="match_parent"
                android:id="@+id/efname"
                android:hint="Name"/>
            </android.support.design.widget.TextInputLayout>
            <android.support.design.widget.TextInputLayout
                android:layout_height="wrap_content"
                android:layout_width="match_parent">
                <EditText
                    android:layout_height="wrap_content"
                    android:layout_width="match_parent"
                    android:id="@+id/dob"
                    android:hint="Date of Birth"/>
            </android.support.design.widget.TextInputLayout>
            <android.support.design.widget.TextInputLayout
                android:layout_height="wrap_content"
                android:layout_width="match_parent">
                <EditText
                    android:layout_height="wrap_content"
                    android:layout_width="match_parent"
                    android:id="@+id/reuname"
                    android:hint="Username"/>
            </android.support.design.widget.TextInputLayout>
            <android.support.design.widget.TextInputLayout
                android:layout_height="wrap_content"
                android:layout_width="match_parent">
                <EditText
                    android:layout_height="wrap_content"
                    android:layout_width="match_parent"
                    android:id="@+id/repass"
                    android:hint="Password"
                    android:inputType="textPassword"/>
            </android.support.design.widget.TextInputLayout>
            <android.support.design.widget.TextInputLayout
                android:layout_height="wrap_content"
                android:layout_width="match_parent">
                <EditText android:layout_height="wrap_content"
                    android:layout_width="match_parent"
                    android:id="@+id/eemail"
                    android:hint="Email"/>
            </android.support.design.widget.TextInputLayout>
            <android.support.design.widget.TextInputLayout
                android:layout_height="wrap_content"
                android:layout_width="match_parent">
                <EditText android:layout_height="wrap_content"
                    android:layout_width="match_parent"
                    android:id="@+id/pphoneno"
                    android:hint="Phone No"
                    android:inputType="number"/>
            </android.support.design.widget.TextInputLayout>
            <android.support.design.widget.TextInputLayout
                android:layout_height="wrap_content"
                android:layout_width="match_parent">
                <EditText
                    android:layout_height="wrap_content"
                    android:layout_width="match_parent"
                    android:id="@+id/paddress"
                    android:hint="Address"/>
            </android.support.design.widget.TextInputLayout>
            <android.support.design.widget.TextInputLayout
                android:layout_height="wrap_content"
                android:layout_width="match_parent"
                >
                <EditText
                    android:layout_height="wrap_content"
                    android:layout_width="match_parent"
                    android:id="@+id/pbldgrp"
                    android:hint="Blood Group"/>
            </android.support.design.widget.TextInputLayout>
            <android.support.design.widget.TextInputLayout
                android:layout_height="wrap_content"
                android:layout_width="match_parent">
                <EditText
                    android:layout_height="wrap_content"
                    android:layout_width="match_parent"
                    android:id="@+id/pemc1"
                    android:hint="Emergency Contact No1"
                    android:inputType="number"/>
            </android.support.design.widget.TextInputLayout>
            <android.support.design.widget.TextInputLayout
                android:layout_height="wrap_content"
                android:layout_width="match_parent">
                <EditText
                    android:layout_height="wrap_content"
                    android:layout_width="match_parent"
                    android:id="@+id/pemc2"
                    android:hint="Emergency Contact No2"
                    android:inputType="number"/>
            </android.support.design.widget.TextInputLayout>
        </LinearLayout>
    </LinearLayout>
</ScrollView>
activity+_main.xml:-
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.uniqval.registration.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />
    <LinearLayout android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/relativeLayout1" android:weightSum="2" android:layout_gravity="bottom">
    <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:background="@drawable/round" android:id="@+id/submit" android:layout_marginRight="5dp" android:layout_marginLeft="5dp" android:layout_weight="1" android:text="Submit"/>



     <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:background="@drawable/round" android:id="@+id/cancel" android:layout_weight="1" android:text="Cancel" android:layout_toRightOf="@id/submit"/>
    </LinearLayout>
    </android.support.design.widget.CoordinatorLayout>

1 个答案:

答案 0 :(得分:0)

在xml中:

<EditText
        android:id="@+id/edit_blood_group"
        style="@style/edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/msg_blood_group"
        android:maxLength="3"
        android:digits="aboABO+-"/>

在验证码中:

public static boolean isBloodGroupValid(String bloodGroup, Context context){
        if(bloodGroup != null) {
            String[] bloodGroups = context.getResources().getStringArray(R.array.blood_groups);
            int len = bloodGroups.length;
            for (int i = 0; i < len; i++) {
                if(bloodGroup.equalsIgnoreCase(bloodGroups[i]))
                    return true;
            }
        }return false;
    }

在strings.xml中

<string-array name="blood_groups">
        <item>O+</item>
        <item>O-</item>
        <item>A+</item>
        <item>A-</item>
        <item>B+</item>
        <item>B-</item>
        <item>AB+</item>
        <item>AB-</item>
    </string-array>

或者,您也可以定义一个带有数组中预先填充项的微调器,这样就没有人可以输入无效值。

检查年龄是否在18至24岁之间的示例:

public static boolean isDOBInRange(String dateStr) {
        try {
            Calendar calMin = Calendar.getInstance();
            calMin.add(Calendar.YEAR, -Constants.MAX_AGE_LIMIT); //24
            Date dateStart = calMin.getTime();

            Calendar calMax = Calendar.getInstance();
            calMax.add(Calendar.YEAR, -Constants.MIN_AGE_LIMIT); //18
            Date dateEnd = calMax.getTime();

            DateFormat format = new SimpleDateFormat("dd-MM-yyyy");
            Date date = format.parse(dateStr);

            if (date != null && dateStart != null && dateEnd != null) {
                if (date.after(dateStart) && date.before(dateEnd)) {
                    return true;
                } else {
                    return false;
                }
            }
            return false;
        } catch (Exception e) {
            return false;
        }
    }

修改日期格式&amp;相应的年龄限制。