[英]javascript validation - only allow one capital letter
我需要添加一些验证,该验证将只允许字符串中可能包含空格的大写字母。 大写字母可以在字符串中的任何位置,但只能使用一次或根本不使用。
我打算将下面的解决方案作为一个单独的规则合并,但是我有一些验证,想知道是否可以对其进行调整以得到所需的结果:
// 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]*$/)
正则表达式像这样分解...
字符串( ^
)的开头,然后是非大写字母( [^AZ]
)零次或多次( *
),然后是可选( ?
)大写字母( [AZ]
),然后[AZ]
大写字母( [^AZ]
)零或更多次( *
),后跟字符串结尾( $
)
编辑:基于@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
}
正则表达式匹配所有大写字母,并返回匹配项数组。 数组的长度是有多少个大写字母,因此小于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;
}
}
我希望我能有所帮助。
您可以循环浏览每个字符以检查其是否等于65至94的ASCII码吗?
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.