Reputation: 235
I am using AngularJS directive for my form input validation .Is there a way to make my regex allow only one special character(:)along with numbers and alphabets . This is the directive i found on stackoverflow.
myapp.directive('noSpecialChar', function() {
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function(inputValue) {
if (inputValue == null)
return ''
cleanInputValue = inputValue.replace(/[^\w\s]/gi, '');
cleanInputValue = cleanInputValue.toUpperCase();
if (cleanInputValue != inputValue) {
modelCtrl.$setViewValue(cleanInputValue);
modelCtrl.$render();
}
return cleanInputValue;
});
}
}
});
I tried adding colon at the end , but i'm unable to reach my solution .
Upvotes: 2
Views: 2340
Reputation: 626689
Use .replace(/^([^:]*:)|\W/g, function($0,$1) { return $1 ? $1.replace(/\W+/g,'')+':' : ''; })
instead of .replace(/\W/gi, '')
See the following demo:
var s = "(*a word : 156,567-354 *)";
console.log(s.replace(/^([^:]*:)|\W/g, function($0,$1) { return $1 ? $1.replace(/\W+/g,'')+':' : ''; }));
The /^([^:]*:)|[^\w\s]/g
regex will match and capture into Group 1 0+ chars other than :
and a :
, OR will match any char that is not a word or whitespace. If Group 1 matched, the whole contents is stripped from the chars other than word and whitespace chars and a :
is added, else, the matched chars with [^\w\s]
are removed.
Upvotes: 1
Reputation: 178
Based on your current code, you're looking to replace everything that is not a letter, number, or white space character.
That said, the regex [^\w\s:]
should work.
\w
= a-z, A-Z, 0-9
\s
= white space characters \r\n\t\f\v
I would even consider removing the \s
as it would allow spaces in your input, unless that is your intention.
Upvotes: 2