簡體   English   中英

檢查字符串是否為空文本或數字的方法不起作用

[英]Method for checking if string is getting empty text or numbers isn't working

我在android中使用此檢查,並使用新的浮動標簽來編輯文本和方法,方法如下。 如果字符串獲取空文本或數字,我將設置一條錯誤消息以編輯文本。 如果我只檢查string是否為空,它會工作,但是當我嘗試檢查string是否得到一些數字時,它就無法工作。 這是我的代碼:

private boolean validateLastName() {
    String checkLastName = inputLastName.getText().toString();
    if (checkLastName.trim().isEmpty())
        for (int i = 0; i < checkLastName.length(); i++) {
            if (!Character.isLetter(checkLastName.charAt(i))) {
                inputLayoutLastName.setError(getString(R.string.err_msg_last_name));
                requestFocus(inputLastName);
                return false;
            } else {
                inputLayoutLastName.setErrorEnabled(false);
            }
        }
    return true;
}

這就是我的使用方式:

if (!validateLastName()) {
        return;
    }

編輯:

例如,這工作正常,但是上面的代碼什么都不做,下面的代碼顯示錯誤(我的意思是給用戶一條錯誤消息):

private boolean validateName() {
    if (inputName.getText().toString().trim().isEmpty()) {
        inputLayoutName.setError(getString(R.string.err_msg_name));
        requestFocus(inputName);
        return false;
    } else {
        inputLayoutName.setErrorEnabled(false);
    }
    return true;
}

在您的解決方案中進行較小的更改后,我認為它會起作用。 我沒有在android中嘗試過,但是為了驗證邏輯,我在java(沒有android)中嘗試了類似的東西。

private boolean validateLastName() { String checkLastName = inputLastName.getText().toString().trim(); if (checkLastName.isEmpty()) { inputLayoutLastName.setError(getString(R.string.err_msg_last_name)); requestFocus(inputLastName); return false; } else { for (int i = 0; i < checkLastName.length(); i++) { if (!Character.isLetter(checkLastName.charAt(i))) { inputLayoutLastName.setError(getString(R.string.err_msg_last_name)); requestFocus(inputLastName); return false; } } } inputLayoutLastName.setErrorEnabled(false); return true; }

if (!validateLastName()) { return; }

更改它以return !validateLastName();

編輯:您實際上甚至不檢查您的if測試中的數字,這就是為什么如果有數字它不會返回false的原因。

private final CharSequence NUMBERS = "0123456789"; if (inputName.getText().toString().trim().isEmpty() && inputName.getText().toString.contains(NUMBERS)) { }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM