输入文本字段的正则表达式验证

时间:2018-03-21 15:47:23

标签: javascript

我必须编写一个正则表达式,使输入文本字段为字母数字,并且不允许在开头和结尾处使用连字符,但可以在字符串中间接受连字符

1 个答案:

答案 0 :(得分:0)

试试这个正则表达式[a-zA-Z0-9]([a-zA-Z0-9\-]*[a-zA-Z0-9])?

var pattern=/[a-zA-Z0-9]([a-zA-Z0-9\-]*[a-zA-Z0-9])?/g;

console.log(pattern.test("ab1"));
console.log(pattern.test("-sd"));
console.log(pattern.test("a-1"));
console.log(pattern.test("d-"));

正则表达式的解释: -

[a-zA-Z0-9]    ---> first character must be alphnumeric
[a-zA-Z0-9\-]* ---> zero or more character which is alphanumeric and -
[a-zA-Z0-9]    ---> last character must be alphnumeric
([a-zA-Z0-9\-]*[a-zA-Z0-9])?  ---> either no character or last character must be alphanumeric and all the other alphanumeric and -