不要在 angularjs 的文本区域中输入超过 20 个逗号分隔或换行分隔的序列号和字母数字

Don't Input more than 20 comma separated or new-line separated serial no and alpha-numeric in textarea in angularjs

这是我的问题陈述。任何帮助都会很棒。

允许用户在具有以下限制的文本区域中输入文本。

我的方法:
Trim所有空格在前。
将所有新行 (/n) 字符替换为逗号 (,)。如果它已经是逗号分隔的条目,那么转换将不会产生任何影响。
计算长度,超过20就报警

这是我迄今为止尝试过的方法,但不知何故捕获和替换新行不起作用。

正在寻找满足以上所有条件的更好的解决方案。谢谢

function checkValidations(newValue) {
                    $ctrl.serialNos = newValue;
                    
                    var comma = "";                     
                    if($ctrl.serialNos) {
                    comma = $ctrl.serialNos.replace(/\s/g, "");
                    comma = $ctrl.serialNos.replace(/\n/g, ",");
                    comma = comma.split(",");
                    
                    
                    var alphaNumeric = /^[(a-z)(A-Z)(0-9),]+$/;
                    if($ctrl.serialNos) {
                    if(!($ctrl.serialNos.match(alphaNumeric))) {
                        alert("Please enter only Alphanumeric values")
                        }
                    }
                    
                    if (comma.length > 21 ) {                           
                        alert("You can not enter More than 20 serial nos");
                    }

\s 匹配所有空格,包括新行,因此您需要先替换新行。

comma = $ctrl.serialNos.replace(/\n+/g, ",");
comma = comma.replace(/\s/g, "");

您可以匹配一个字母数字条目,并重复 0 - 19 次字母数字条目,该条目前面可以有 1 个或多个换行符或逗号

^[a-zA-Z0-9]+(?:(?:[\r\n]+|,)[a-zA-Z0-9]+){0,19}$

说明

  • ^ 字符串开头
  • [a-zA-Z0-9]+ 匹配任何列出的(字母数字条目)1 次以上
  • (?:非捕获组
    • (?:[\r\n]+|,) 匹配 1+ 个换行符或单个逗号
    • [a-zA-Z0-9]+ 匹配任何列出的字符 1 次以上
  • ){0,19}关闭非捕获组重复0-19次
  • $ 字符串结束

Regex demo

您可以使用 test 检查有效输入

if (!pattern.test(s)) {
    // ...
}