Regular expression to accept only characters (a-z) in a textbox

后端 未结 8 1422
北荒
北荒 2021-01-05 12:16

What is a regular expression that accepts only characters ranging from a to z?

8条回答
  •  迷失自我
    2021-01-05 13:05

    None of the answers exclude special characters... Here is regex to ONLY allow letters, lowercase and uppercase.

    /^[_A-zA-Z]*((-|\s)*[_A-zA-Z])*$/g
    

    And as for different languages, you can use this function to convert letters to english letters before the check, just replace returnString.replace() with letters you need.

    export function convertString(phrase: string) {
        var maxLength = 100;
    
        var returnString = phrase.toLowerCase();
        //Convert Characters
        returnString = returnString.replace("ą", "a");
        returnString = returnString.replace("č", "c");
        returnString = returnString.replace("ę", "e");
        returnString = returnString.replace("ė", "e");
        returnString = returnString.replace("į", "i");
        returnString = returnString.replace("š", "s");
        returnString = returnString.replace("ų", "u");
        returnString = returnString.replace("ū", "u");
        returnString = returnString.replace("ž", "z");
    
        // if there are other invalid chars, convert them into blank spaces
        returnString = returnString.replace(/[^a-z0-9\s-]/g, "");
        // convert multiple spaces and hyphens into one space
        returnString = returnString.replace(/[\s-]+/g, " ");
        // trims current string
        returnString = returnString.replace(/^\s+|\s+$/g, "");
        // cuts string (if too long)
        if (returnString.length > maxLength) returnString = returnString.substring(0, maxLength);
        // add hyphens
        returnString = returnString.replace(/\s/g, "-");
    
        return returnString;
    }
    

    Usage:

    const firstName = convertString(values.firstName);
    
                if (!firstName.match(allowLettersOnly)) {
                }
    

提交回复
热议问题