Javascript验证-只允许一个大写字母

javascript validation - only allow one capital letter

本文关键字:许一个 大写字母 -只 验证 Javascript      更新时间:2023-09-26

我需要添加一些验证,在可能包含空格的字符串中只允许一个大写字母。大写字母可以出现在字符串的任何位置,但只能使用一次,或者根本不使用。

我打算将下面的解决方案合并为一个单独的规则,但我有这一点验证,想知道我是否可以调整它以获得所需的结果:

// Validate Sentence Case
if(dataEntryCaseId.toString().match("4")){
    var newValue = toTitleCase(value);
    if(newValue != value){
        for(var x = 1, j = value.length; x < j; x++){
            if(value.charAt(x) != newValue.charAt(x)){
                valid = false;
                $("#text_10").attr({"value":$("#text_10").attr("value").replace(value.charAt(x), "")});
                finalVal = finalVal.replace(value.charAt(x), "");
            }
        }
    }
}

if(!valid){
    for(var x = 0, j = styleNoteJsonData.styleGroupNote.length; x < j; x++){
        if(styleNoteJsonData.styleGroupNote[x].styleName == styleGroupName){
            alert(styleNoteJsonData.styleGroupNote[x].styleNote);           
            $(".styleNote").addClass("alertRed");
            SendErrorMessage(styleNoteJsonData.styleGroupNote[x].styleNote);                
        }
    }
"this is A way to do it with regex".match(/^[^A-Z]*[A-Z]?[^A-Z]*$/)

正则表达式解析如下:

字符串的开始(^)后跟非大写字母([^A-Z])零次或多次(*),后跟可选(?)大写字母([A-Z]),后跟非大写字母([^A-Z])零次或多次(*),后跟字符串的结束($)


编辑:基于@IAbstractDownvoteFactory的答案的想法的更简单的方法

var string = "This is a simple way to do it"
// match all capital letters and store in array x
var x = string.match(/[A-Z]/g)
// if x is null, or has length less than 2 then string is valid
if(!x || x.length < 2){
    // valid
} else {
    // not valid
}

Regex匹配所有大写字母,并返回一个匹配数组。数组的长度是大写字母的个数,所以小于2返回true

这个怎么样:

var string = "A string";
if(string.split(/[A-Z]/).length <= 2) {
    // all good
}
else {
    // validation error
}

用大写字母分割字符串。如果长度为2,则只有一个大写字母

你可以试一下:

function checkCapitals(InputString)
{
    // Counter to track how many capital letters are present
    var howManyCapitals = 0;
    // Loop through the string
    for (i = 0; i < InputString.length; i++)
    {
        // Get each character of the string
        var character = InputString[i];
        // Check if the character is equal to its uppercase version and not a space
        if (character == character.toUpperCase() && character != ' ') {
         // If it was uppercase, add one to the uppercase counter
         howManyCapitals++;
        }
    }
        // Was there more than one capital letter?
        if (howManyCapitals > 1)
        {
             // Yes there was! Tell the user.
             alert("You have too many capital letters!");
             return false;
        }
}

希望我能帮到你。

你能遍历每个字符来检查它是否等于ascii码65到94吗?

var CharArr = "mystring".toCharArray();
var countCapsChars = 0;
for(var i =0;i<= CharArr.length;i++) {
if (CharArr[i].CharCodeAt(0) >= 65 && CharArr[i].CharCodeAt(0) <=94) {
  countCapsChars++;
}
if (countCapsChars == 1 || countCapsChars == 0){
//pas
}
else 
{
//fail
}
相关文章: