Search code examples
kotlin

Checking if a string has no special characters except for ".", "_" and "@"


I'm currently writing a script which checks username & password validity. The username should have between 3 and 20 characters and no special characters, except for ".", "_" and "@".

Currently, this is my function:

fun isValidUsername(username: String): Boolean {
    var usrnmlength = true
    var usrnmspecial = true
    
    if ((username.length < 3) or (username.length > 20)) { usrnmlength = false }
    if (username.filter { !it.isLetterOrDigit() }.firstOrNull() != null) {usrnmspecial = false}

    return if ((usrnmlength) and (usrnmspecial)) {
        (true)
    } else {
        (false)
    }

}

It checks, if the username has between 3 and 20 characters and if the username has no special characters. But it also says that the username is not valid, if there are the special characters ".", "_" and "@". These should be allowed. How can I do this?


Solution

  • You can modify the condition for checking special characters to allow ".", "_", and "@" while filtering out other special characters. Here's the updated function:

    fun isValidUsername(username: String): Boolean {
    var usrnmlength = true
    var usrnmspecial = true
    
    if ((username.length < 3) or (username.length > 20)) { 
        usrnmlength = false 
    }
    
    if (username.filter { !(it.isLetterOrDigit() || it in listOf('.', '_', '@')) }.firstOrNull() != null) {
        usrnmspecial = false
    }
    
    return usrnmlength && usrnmspecial
    

    }

    This modification ensures that the username is considered valid if it has between 3 and 20 characters and contains only letters, digits, ".", "_", or "@".