Reputation: 7148
I'm trying to validate name which contains "alphanumeric characters, supported symbols, and space". Here I need to allow only a single hyphen(-)
, but not a double hyphen(--)
.
This is my code as follows:
$.validator.addMethod(
'alphanumeric_only',
function (val, elem) {
return this.optional(elem) || /^[^*~<^>+(\--)/;|.]+$/.test(val);
},
$.format("shouldn't contain *.^~<>/;|")
);
The above code, doesn't even allow a single hyphen(-)
. How do I allow a single hyphen, but prevent a double hyphen. Any help is greatly appreciated.
Upvotes: 2
Views: 333
Reputation: 1882
I advise you to use white list instead of blacklist. However this is working:
<input type="text" id="validate"/>
<script>
$('#validate').keyup(function(){
val = this.value;
if(/([*.^~<>/;|]|--)/.test(val)) this.style.backgroundColor='red';
else this.style.backgroundColor='';
});
</script>
Upvotes: 4
Reputation: 336468
For this, you need a negative lookahead assertion:
/^(?!.*--)[^*~<^>+()\/;|.]+$/
should do it.
Explanation:
^ # Start of string
(?! # Assert it's impossible to match the following:
.* # any string, followed by
-- # two hyphens
) # End of lookahead
[^*~<^>+()\/;|.]+ # Match a string consisting only of characters other than these
$ # End of string
Not that this might fail if your string can contain newlines. If it can, use
/^(?![\s\S]*--)[^*~<^>+()\/;|.]+$/
Upvotes: 6