Skip to content

Instantly share code, notes, and snippets.

@mzfkr97
Forked from KalpeshTalkar/Validator.kt
Created March 1, 2021 14:10
Show Gist options
  • Save mzfkr97/79b99940f86eded0585b7ee5f26ccd3e to your computer and use it in GitHub Desktop.
Save mzfkr97/79b99940f86eded0585b7ee5f26ccd3e to your computer and use it in GitHub Desktop.
A validator class written in Kotlin can be used to validate the data. Eg. checks for valid email, phone, password, name, etc.
//
// Copyright © 2018 Kalpesh Talkar. All rights reserved.
//
// 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.
//
// For support: https://gist.github.com/KalpeshTalkar/e6a50efd08a3d5d142e47da559936bb7
//
import android.support.design.widget.TextInputLayout
import android.util.Patterns
import android.widget.EditText
import java.util.regex.Pattern
/**
* Created by Kalpesh on 23/01/18.
*
* This class is used to validate data like email, phone, password policy, etc.
* It also sets error to the EditText or TextInputLayout of the EditText if needed.
*/
class Validator {
companion object {
// Default validation messages
private val PASSWORD_POLICY = """Password should be minimum 8 characters long,
|should contain at least one capital letter,
|at least one small letter,
|at least one number and
|at least one special character among ~!@#$%^&*()-_=+|[]{};:'\",<.>/?""".trimMargin()
private val NAME_VALIDATION_MSG = "Enter a valid name"
private val EMAIL_VALIDATION_MSG = "Enter a valid email address"
private val PHONE_VALIDATION_MSG = "Enter a valid phone number"
/**
* Retrieve string data from the parameter.
* @param data - can be EditText or String
* @return - String extracted from EditText or data if its data type is Strin.
*/
private fun getText(data: Any): String {
var str = ""
if (data is EditText) {
str = data.text.toString()
} else if (data is String) {
str = data
}
return str
}
/**
* Checks if the name is valid.
* @param data - can be EditText or String
* @param updateUI - if true and if data is EditText, the function sets error to the EditText or its TextInputLayout
* @return - true if the name is valid.
*/
fun isValidName(data: Any, updateUI: Boolean = true): Boolean {
val str = getText(data)
val valid = str.trim().length > 2
// Set error if required
if (updateUI) {
val error: String? = if (valid) null else NAME_VALIDATION_MSG
setError(data, error)
}
return valid
}
/**
* Checks if the email is valid.
* @param data - can be EditText or String
* @param updateUI - if true and if data is EditText, the function sets error to the EditText or its TextInputLayout
* @return - true if the email is valid.
*/
fun isValidEmail(data: Any, updateUI: Boolean = true): Boolean {
val str = getText(data)
val valid = Patterns.EMAIL_ADDRESS.matcher(str).matches()
// Set error if required
if (updateUI) {
val error: String? = if (valid) null else EMAIL_VALIDATION_MSG
setError(data, error)
}
return valid
}
/**
* Checks if the phone is valid.
* @param data - can be EditText or String
* @param updateUI - if true and if data is EditText, the function sets error to the EditText or its TextInputLayout
* @return - true if the phone is valid.
*/
fun isValidPhone(data: Any, updateUI: Boolean = true): Boolean {
val str = getText(data)
val valid = Patterns.PHONE.matcher(str).matches()
// Set error if required
if (updateUI) {
val error: String? = if (valid) null else PHONE_VALIDATION_MSG
setError(data, error)
}
return valid
}
/**
* Checks if the password is valid as per the following password policy.
* Password should be minimum minimum 8 characters long.
* Password should contain at least one number.
* Password should contain at least one capital letter.
* Password should contain at least one small letter.
* Password should contain at least one special character.
* Allowed special characters: "~!@#$%^&*()-_=+|/,."';:{}[]<>?"
*
* @param data - can be EditText or String
* @param updateUI - if true and if data is EditText, the function sets error to the EditText or its TextInputLayout
* @return - true if the password is valid as per the password policy.
*/
fun isValidPassword(data: Any, updateUI: Boolean = true): Boolean {
val str = getText(data)
var valid = true
// Password policy check
// Password should be minimum minimum 8 characters long
if (str.length < 8) {
valid = false
}
// Password should contain at least one number
var exp = ".*[0-9].*"
var pattern = Pattern.compile(exp, Pattern.CASE_INSENSITIVE)
var matcher = pattern.matcher(str)
if (!matcher.matches()) {
valid = false
}
// Password should contain at least one capital letter
exp = ".*[A-Z].*"
pattern = Pattern.compile(exp)
matcher = pattern.matcher(str)
if (!matcher.matches()) {
valid = false
}
// Password should contain at least one small letter
exp = ".*[a-z].*"
pattern = Pattern.compile(exp)
matcher = pattern.matcher(str)
if (!matcher.matches()) {
valid = false
}
// Password should contain at least one special character
// Allowed special characters : "~!@#$%^&*()-_=+|/,."';:{}[]<>?"
exp = ".*[~!@#\$%\\^&*()\\-_=+\\|\\[{\\]};:'\",<.>/?].*"
pattern = Pattern.compile(exp)
matcher = pattern.matcher(str)
if (!matcher.matches()) {
valid = false
}
// Set error if required
if (updateUI) {
val error: String? = if (valid) null else PASSWORD_POLICY
setError(data, error)
}
return valid
}
/**
* Sets error on EditText or TextInputLayout of the EditText.
* @param data - Should be EditText
* @param error - Message to be shown as error, can be null if no error is to be set
*/
private fun setError(data: Any, error: String?) {
if (data is EditText) {
if (data.parent.parent is TextInputLayout) {
(data.parent.parent as TextInputLayout).setError(error)
} else {
data.setError(error)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment