3

我正在尝试在 android 中找到一个表单验证库。有这样的事吗?

我有一个注册表单,我想验证它的字段。如果用户输入了无效数据,我想在该字段的右侧放置一个红色警告标记,并弹出一个他输入了无效数据的工具提示。

我知道,android:inputType但这不是我想要的

4

5 回答 5

2

我不知道任何这样的图书馆。但是,如果您正在使用 EditTexts,那么您最好的选择是使用自定义TextWatcher

class TextCheck implements TextWatcher
{
    private EditText editor;

    public TextCheck(EditText editor)
    {
        this.editor = editor;
    }

    @Override
    public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
    {
        // check the text, and if the user entered 
        // something wrong, change your edittext
        if(something wrong)
        {
            editor.setBackgroundColor(Color.RED); //for example
        }
    }

    @Override
    public void afterTextChanged(Editable arg0){}

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3){}


}

然后你可以在你所有的 EditTexts 上使用它,比如

EditText editor = (EditText) findViewById(...your id...);
editor.addTextChangedListener(new TextCheck(editor));
于 2012-08-08T09:26:34.800 回答
2

有这样的事吗?

啊..是的,有一个,你可以在这里找到它。

它使用但不限于Annotations为您进行表单验证。要了解该库的功能,请访问关于 SO 的以下答案,其中我描述了该库的用法。

如果您想编写新规则,您可以随时扩展Rule类。

PS:我是图书馆的作者。

于 2012-10-29T05:59:12.477 回答
1

我知道这是旧的,但你可以尝试这个优秀的Android 验证库并访问这个Stackoverflow 参考和这个Stackoverflow 参考以获取使用示例,因为我发现主要库的操作方法有点难以理解。

于 2015-02-18T10:04:50.777 回答
0

我做了类似的事情。您可以改进此代码并适应您的需要。

EditTextWithValidation.java

public class EditTextWithValidation extends EditText implements OnTouchListener {
    private EditTextValidator mValidator;

    public EditTextWithValidation(Context context) {
        super(context);

        initialize();
    }

    public EditTextWithValidation(Context context, AttributeSet attrs) {
        super(context, attrs);

        initialize();
    }

    public EditTextWithValidation(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        initialize();
    }

    public EditTextValidator getCustomValidator() {
        return mValidator;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        setError(null);

        return false;
    }

    private void initialize() {
        mValidator = new EditTextValidator(this);
        setOnTouchListener(this);
    }
}

EditTextValidator.java

public class EditTextValidator {
    private static final String TAG = EditTextValidator.class.getName();

    private enum ValidationResult {
        Ok, Rules, Mismatch
    }

    private EditText mParent;
    private Pattern mValidationPattern;
    private int mValidationErrorMsgId;
    private boolean mAllowEmpty;
    private EditText mMatchView;
    private int mMismatchMsgId;
    private int mMinLength;
    private int mMaxLength;
    private ValidationResult mValidationResult;

    public EditTextValidator(EditText parent) {
        this.mParent = parent;
    }

    public void setAllowEmpty(boolean allowEmpty) {
        this.mAllowEmpty = allowEmpty;
    }

    public void setValidationErrorMsgId(int validationErrorMsgId) {
        this.mValidationErrorMsgId = validationErrorMsgId;
    }

    public void setValidationRules(String strPattern, int validationErrorMsgId, boolean allowEmpty) {
        try {
            if (!TextUtils.isEmpty(strPattern)) {
                mValidationPattern = Pattern.compile(strPattern);
            }
        } catch (PatternSyntaxException e) {
            Log.e(TAG, e.getMessage(), e);
            ToastUtil.toastShort("Invalid validation pattern!");
        }

        this.mValidationErrorMsgId = validationErrorMsgId;
        this.mAllowEmpty = allowEmpty;
    }

    public void setValidLength(int min, int max) {
        mMinLength = min;
        mMaxLength = max;
    }

    public void shouldMatch(EditText matchView, int mismatchMsgId) {
        this.mMatchView = matchView;
        this.mMismatchMsgId = mismatchMsgId;
    }

    public boolean validate() {
        mValidationResult = ValidationResult.Ok;

        InputMethodManager imm = (InputMethodManager) mParent.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mParent.getWindowToken(), 0);

        final String text = mParent.getText().toString();
        final int length = text.length();

        if (mValidationResult == ValidationResult.Ok && !mAllowEmpty && 0 == text.length()) {
            mValidationResult = ValidationResult.Rules;
        }

        if (mValidationResult == ValidationResult.Ok) {
            if (mMinLength != 0 && length < mMinLength) {
                mValidationResult = ValidationResult.Rules;
            } else if (mMaxLength != 0 && length > mMaxLength) {
                mValidationResult = ValidationResult.Rules;
            }
        }

        if (mValidationResult == ValidationResult.Ok && mValidationPattern != null) {
            Matcher m = mValidationPattern.matcher(text);
            if (!m.matches())
                mValidationResult = ValidationResult.Rules;
        }

        if (mValidationResult == ValidationResult.Ok && mMatchView != null) {
            if (mMatchView.getText().toString().compareTo(text) != 0)
                mValidationResult = ValidationResult.Mismatch;
        }

        if (ValidationResult.Ok == mValidationResult) {
            mParent.setError(null);
        } else {
            CharSequence error = null;
            if (ValidationResult.Rules == mValidationResult)
                error = MyApplication.getContext().getText(mValidationErrorMsgId);
            else if (ValidationResult.Mismatch == mValidationResult)
                error = MyApplication.getContext().getText(mMismatchMsgId);

            mParent.setError(error);
            mParent.requestFocus();
        }

        return mValidationResult == ValidationResult.Ok;
    }
}

用法:

mSignupEmail = (EditTextWithValidation) root.findViewById(R.id.signup_email);
mSignupEmail.getCustomValidator().setValidationRules(
        "[a-zA-Z0-9_-]+(?:\\.[a-zA-Z0-9_-]+)*@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9_-]+)*\\.(?:[a-zA-Z]{2,})",
        R.string.email_answer_validation_msg,
        false);
mSignupEmail.getCustomValidator().setValidLength(0, 50);

…

mSignupPassword = (EditTextWithValidation) root.findViewById(R.id.signup_password);
mSignupPassword.getCustomValidator().setValidationRules(
                    "[a-zA-Z0-9!@#$%^&*()]{6,20}",
        R.string.password_validation_msg,
        false);

…

mSignupConfirmPassword = (EditTextWithValidation) root.findViewById(R.id.signup_confirm_password);
mSignupConfirmPassword.getCustomValidator().setAllowEmpty(true);
mSignupConfirmPassword.getCustomValidator().shouldMatch(mSignupPassword, R.string.password_mismatch);
mSignupConfirmPassword.getCustomValidator().setValidationErrorMsgId(R.string.password_validation_msg);

…

if (mSignupEmail.getCustomValidator().validate() && mSignupPassword.getCustomValidator().validate() && mSignupConfirmPassword.getCustomValidator().validate()) {
    // DO SOMETHING
}
于 2012-08-08T09:32:57.527 回答
0

安装此应用程序:https ://play.google.com/store/apps/details?id=com.desarrollodroide.repos

转到:Utils-> Android-Validator->View Demo

这个应用程序中还有很多其他很酷的库。好消息是您可以查看每个库的演示,如果您喜欢,还可以获取该特定库的 github 存储库的链接。它非常有用。

于 2013-08-21T14:26:28.867 回答