Skip to content

Instantly share code, notes, and snippets.

@KalpeshTalkar
Last active October 2, 2022 09:42
Show Gist options
  • Save KalpeshTalkar/e6a50efd08a3d5d142e47da559936bb7 to your computer and use it in GitHub Desktop.
Save KalpeshTalkar/e6a50efd08a3d5d142e47da559936bb7 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)
}
}
}
}
}
@cyberespia
Copy link

It would be so nice to give an example of how to use these functions, I tried with.

       val email = findViewById<EditText>(R.id.email)
        println(isValidEmail(email))

@KalpeshTalkar
Copy link
Author

Usage:

// To validate email address:
// You can pass string or edit text as a parameter.
// If you need to show error on your edit text or text input layout, pass the second parameter as true else false.
Validator.isValidEmail(YOUR_EDIT_TEXT_OR_STRING, SHOW_ERROR_FLAG)

// Below code checks if the passed string is a valid email or not.
Validator.isValidEmail("name@domain.com", false)

// Below code checks if the passed edit text has a valid email or not.
// If the email is not valid, error will be show on the edit text.
Validator.isValidEmail(etEmail, true)

@KalpeshTalkar
Copy link
Author

It would be so nice to give an example of how to use these functions, I tried with.

       val email = findViewById<EditText>(R.id.email)
        println(isValidEmail(email))

@cyberespia Thank you for having a look at my gists.
I have shown usage example in my comment.

@elijellyeli
Copy link

IsValidPassword always returns true (line 180).
should be

return valid

@KalpeshTalkar
Copy link
Author

IsValidPassword always returns true (line 180).
should be

return valid

@elijellyeli Oops! my bad. Thanks for pointing out the error. Updated the file.

@swarn756
Copy link

how to use

@KalpeshTalkar
Copy link
Author

how to use

Please check the comments above to see the usage and example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment