我必须对特定的文本值进行验证。如果字符串为空,我必须返回,因为请输入一些值。文本字段应允许字母数字字符和特殊字符.@_ .If用户输入任何其他特殊字符,不允许返回除.@_以外的特殊字符。如果他们只输入特殊字符,我必须返回‘不要输入特殊字符’?我尝试了下面的方法,但我没有工作。有什么可以帮忙的吗?
请在此处查看更新的代码。
const test1 = '[^A-Za-z0-9_||@||\. ]';
const test2 = '[A-Za-z0-9]';
const whitespace = '/^\s*$/';
const onlyspecial = '/[.@_ ]/';
if(strval.match(whitespace))
{
return "Please enter value";
}
if(strval.match(test1))
{
if(strval.match(test2)|| strval.match(onlyspecial))
{
return "special character except @,space,underscore and . not allowed";
}
else
{
return "do not enter only special char";
}
}
Results for various input:
strval = "abcd@123" - pass
strval = "abcd_123" - pass
strval= "abcd test" - pass
strval = "abcd.test - pass
strval = .@_ - do not enter only special char (though it is acceptable characters, only entering these should not accept)
strval = "abcd$%^" - special character except @,space,underscore and . not allowed
strval = "abcs2323&&" - special character except @,space,underscore and . not allowed
strval = "$$$%%^&&" - do not enter only special char
strval = ".@_1234" - please enter valid name
发布于 2018-08-21 06:32:08
替换console.log(...)有了return,它应该可以工作了。
var strVal = 'Abcd';
const onlySpecial = /[@_.]/
const alphaNumeric = /[A-Za-z0-9]/
const alphaNumericSpecial = /[^A-Za-z0-9@_.]/
if (strVal == '') {
console.log("Nop")
} else if (alphaNumericSpecial.test(strVal)) {
console.log("Only Alphanumeric and @, _, .")
}
else {
if (onlySpecial.test(strVal) && alphaNumeric.test(strVal)) {
console.log("Good Character.")
} else if (onlySpecial.test(strVal) && !alphaNumeric.test(strVal)) {
console.log("Don't Enter only special character.")
} else {
console.log("Alphanumeric..")
}
}
发布于 2018-08-21 06:40:42
const test1 = '[^A-Za-z0-9 \S||@||\.||_]';
const test2 = '[A-Za-z0-9]';
const whiteSpace = /^\s*$/;
if (strValue.match(whiteSpace)){
return "Please enter value";
}else if (strValue.match(test1)) {
return "Please enter valid name (except .@_ )";
}else if (!strValue.match(test2)){
return "Don't enter only special characters";
}
https://stackoverflow.com/questions/51934512
复制相似问题