简体   繁体   English

使用javascript将用户输入限制为带有正则表达式的逗号分隔的单词

[英]Limit user input to allowable comma delimited words with regular expression using javascript

I want to force the user to enter any combination of the following words. 我想强迫用户输入以下单词的任意组合。 the words need to be comma delimited and no comma at the beginning or end of the string the user should only be able to enter one of each word. 单词需要用逗号定界,并且在字符串的开头或结尾没有逗号,用户只能输入每个单词之一。

Examples 例子

admin
basic,ectech
admin,ectech,advanced
basic,advanced,admin,ectech

my attempt 我的尝试

^((basic|advanced)|admin|ectech)((,basic|,advanced)|,admin|,ectech){0,2}$

使用regex确实不是一种好方法,因为如果不需要特定的顺序,则regex确实没有一种好的方法来处理“只允许输入给定单词一次”。

I would do a double attack on this. 我会对此双重攻击。 In your validation function, use a regex as well as a JavaScript hashtable to store words that have already been entered so as to prevent duplicates from being entered. 在您的验证功能中,使用正则表达式以及JavaScript哈希表来存储已输入的单词,以防止输入重复的单词。

I would suggest to split your requirement into several parts: 我建议将您的需求分为几个部分:

  1. split the string using the str.split("[,]") and get an array of strings 使用str.split("[,]")分割字符串并获取字符串数组

  2. validate each element of the array using expression like ^(bacic|advanced|..)$ 使用类似^(bacic|advanced|..)$表达式来验证数组的每个元素

  3. use hashtable to put each array element into that and if element is added more than once then fail validation 使用哈希表将每个数组元素放入其中,如果元素被添加多次,则验证失败

EDIT : Actualy in step 2 you can use another hashtable that will store all your words. 编辑 :实际上,在第2步中,您可以使用另一个将存储您所有单词的哈希表。 It will be faster to check against hashtable than to run a regular expression. 检查哈希表要比运行正则表达式更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM