我有一个表单,想要限制第一个和最后一个字符。(javascript) 限制条件如下:
- 输入必须以字母或数字开头和结尾,而中间可以包含下划线。
例如:
Valid Entries: abc, ABC, Abc123, 123a, Abc_12, Abc_12_3a
Invalid Entries: _abc, abc_, _abc_
我尝试按以下方式创建我的正则表达式:
^(?!\_)(?!_*_$)[a-zA-Z0-9_]+$
这不允许在开头使用下划线,这很好,但允许在结尾使用下划线,而我想限制它。
有什么建议吗?
谢谢。
const validEntries = ['abc', 'ABC', 'Abc123', '123a', 'Abc_12', 'Abc_12_3a'];
const invalidEntries = ['_abc', 'abc_', '_abc_'];
const regex = /^(?!\_)(?!_*_$)[a-zA-Z0-9_]+$/;
validEntries.forEach((x) => {
const ret = regex.test(x);
console.log('Should be true :', ret);
});
console.log('-------------------');
invalidEntries.forEach((x) => {
const ret = regex.test(x);
console.log('Should be false :', ret);
});
---已更新---
我在我的AngularJS应用程序中使用正则表达式。
我创建了如下指令:
.directive('restrictField', function () {
return {
require: 'ngModel',
restrict: 'A',
link: function (scope, element, attrs, ctrl) {
var regReplace,
preset = {
'alphanumeric-spl': '\\w_./\s/g',
'alphanumeric-underscore': '\\w_',
'numeric': '0-9',
'alpha-numeric': '\\w'
},
filter = preset[attrs.restrictField] || attrs.restrictField;
ctrl.$parsers.push(function (inputValue) {
regReplace = new RegExp('[^' + filter + ']', 'ig');
if (inputValue == undefined)
return ''
cleanInputValue = inputValue.replace(regReplace, '');
if (cleanInputValue != inputValue) {
ctrl.$setViewValue(cleanInputValue);
ctrl.$render();
}
return cleanInputValue;
});
}
}
})
我在我的HTML中将其使用为:
我正在将其用作我的HTML:
<input type="text" name="uname" ng-model="uname" required class="form-control input-medium" restrict-field="alphanumeric-underscore" ng-trim="false" />
^[a-zA-Z0-9]+(?:_[a-zA-Z0-9]+)*$
- Wiktor Stribiżew(?!.*_$)
而不是(?!_*_$)
。 - Bergi^(?!_)(?!.*_$)[a-zA-Z0-9_]+$
or^[a-zA-Z0-9]([a-zA-Z0-9_]*[a-zA-Z0-9])?$
- Wiktor Stribiżew