AValidations – это библиотека, которую можно напрямую экспортировать в виде jar-пакета.
AValidationsDemo – демонстрационный проект, который позволяет быстро изучить и использовать библиотеку AValidations.
Скачайте zip-архив или клонируйте проект AValidations.
Импортируйте проект в Eclipse, щёлкните правой кнопкой мыши на проекте -> preference -> Android -> library -> Add, выберите проект AValidations и добавьте его, затем примените изменения.
Создайте собственный валидатор, унаследовав класс ValidationExecutor:
public class UserNameValidation extends ValidationExecutor { public boolean doValidate(Context context, String text) { String regex = "^a-zA-Z(?=.*?[0-9])[a-zA-Z0-9_]{7,11}$"; boolean result = Pattern.compile(regex).matcher(text).find(); if (!result) { Toast.makeText(context, context.getString(R.string.e_username_hint), Toast.LENGTH_SHORT).show(); return false; } return true; } }
Используйте EditTextValidator для проверки:
public class LoginActivity extends Activity implements OnClickListener{ private EditText usernameEditText; private EditText passwordEditText; private Button loginButton; private EditTextValidator editTextValidator; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login);
usernameEditText = (EditText) findViewById(R.id.login_username_edittext);
passwordEditText = (EditText) findViewById(R.id.login_password_edittext);
loginButton = (Button) findViewById(R.id.login_button);
loginButton.setOnClickListener(this);
editTextValidator = new EditTextValidator(this)
.setButton(loginButton)
.add(new ValidationModel(usernameEditText,new UserNameValidation()))
.add(new ValidationModel(passwordEditText,new PasswordValidation()))
.execute();
}
@Override public void onClick(View v) { switch (v.getId()) { case R.id.login_button:
if (editTextValidator.validate()) {
Toast.makeText(this, "Проверка пройдена", Toast.LENGTH_SHORT).show();
}
break;
}
}
Если необходимо реализовать эффект, при котором кнопка отправки формы недоступна, пока поля не заполнены, установите setButton(view) и напишите селектор для фона кнопки, например:
Copyright 2014 ken.cai (http://quanke.name)
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Вы можете оставить комментарий после Вход в систему
Неприемлемый контент может быть отображен здесь и не будет показан на странице. Вы можете проверить и изменить его с помощью соответствующей функции редактирования.
Если вы подтверждаете, что содержание не содержит непристойной лексики/перенаправления на рекламу/насилия/вульгарной порнографии/нарушений/пиратства/ложного/незначительного или незаконного контента, связанного с национальными законами и предписаниями, вы можете нажать «Отправить» для подачи апелляции, и мы обработаем ее как можно скорее.
Комментарии ( 0 )