Reputation: 1751
My requirement is that i needs to perform the validation for the input text which should not allow the special characters at start and end of the word and also it shouldn't allow two consecutive special characters in between the word.
For the above mentioned requirement i have found the regex and tested it on regex101.com and it's coming correct but when i wrote in the javascript i am not able to get the desired results.
The snippets are as follows:
$('input').bind('keypress', function (event) {
var re = new RegExp("^[a-z0-9](?!.*?[^\na-z0-9]{2}).*?[a-z0-9]$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (key.match(re)) {
alert("Successful match");
} else {
alert("No match");
return false;
}
});
<input type="text">
But every time i am getting the result as no match. I am not getting where i am getting wrong.
Please help on this.
The JSFiddle link is : Demo for the Regex
Regex sample input - taken from some stackoverflow post
Upvotes: 0
Views: 333
Reputation: 5596
The issue was that you were matching on the most recent character the user inputted against the regex, rather than the whole value of the <input>
.
Try this code instead:
$('input').bind('keypress', function(event) {
var re = new RegExp("^[a-z0-9](?!.*?[^/\na-z0-9]{2}).*?[a-z0-9]$");
// This is now set to the value of the whole <input> element
var key = $('input').val()
if (key.match(re)) {
alert("Successful match")
}
else {
alert("No match")
}
})
Upvotes: 1