如何在angularjs中验证仅具有特殊字符的正则表达式?

时间:2018-08-20 16:00:14

标签: javascript angularjs

我必须对特定的文本值进行验证。如果字符串为空,我必须返回,请输入一些值。文本字段应允许使用字母数字和特殊字符。@ _。如果用户输入任何其他特殊字符,则需要返回特殊字符,但不允许使用。@ _。如果他们仅输入特殊字符,我必须返回“不输入特殊字符”?我尝试了以下方法,但没有解决。有帮助吗?

请在此处查看更新的代码。

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

2 个答案:

答案 0 :(得分:0)

用return替换console.log(...)应该可以。

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..")
    }
}

答案 1 :(得分:0)

     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";
      }