Skip to content

Instantly share code, notes, and snippets.

@keriati
Created August 12, 2012 19:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keriati/3333995 to your computer and use it in GitHub Desktop.
Save keriati/3333995 to your computer and use it in GitHub Desktop.
Detect invalid characters
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.center {
text-align: center;
}
#myInput {
font-size: 24px;
height: 32px;
}
.hl {
color: #4169e1;
}
.valid {
background-color: #adff2f;
}
.invalid {
background-color: #ff69b4;
}
</style>
</head>
<body>
<h1 class="center">Character detection test</h1>
<p class="center">
<br/><br/>
<input type="text" name="myInput" id="myInput"/><br/><br/>
<button>Stupid Button</button><br/><br/>
<span>RegExp: </span><input type="text" name="regexp" id="regexp" value="[a-zA-ZäöüÄÖÜß \.]"/><br/>
<span>Validation: </span><span class="hl" id="valid"></span><br/>
<span id="errormsg"></span>
</p>
<div class="center" id="output">
</div>
<script src="jquery.js"></script>
<script>
(function () {
var $input = $('#myInput'),
$regexp = $('#regexp'),
$valid = $('#valid'),
$errormsg = $('#errormsg');
$input.on('change', function (e) {
var myRegTest,
myRegMatch,
value,
match,
bad = new String(),
pos;
myRegTest = new RegExp('^' + $regexp.val() + '+$', '');
myRegMatch = new RegExp($regexp.val() + '+', 'g');
value = new String($input.val());
if(myRegTest.test(value)) {
$valid.html('True');
$errormsg.html('');
$input.addClass('valid');
return true;
}
bad = value;
match = bad.match(myRegMatch);
if (match !== null ) {
for(var i in match) {
if(match.hasOwnProperty(i)) {
bad = bad.replace(match[i], '');
}
}
}
bad = rmDupes(bad.split('')).join('');
$valid.html('False');
$errormsg.html('Invalid characters: ' + bad);
$input.addClass('invalid');
return false;
});
function rmDupes(arr) {
var i,
out = [],
obj = {};
for (i = 0; i < arr.length; i++) {
obj[arr[i]] = 0;
}
for (i in obj) {
out.push(i);
}
return out;
}
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment