Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 "@".

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading