Skip to content

Instantly share code, notes, and snippets.

@keriati
Created August 10, 2012 20:07
Show Gist options
  • Save keriati/3317440 to your computer and use it in GitHub Desktop.
Save keriati/3317440 to your computer and use it in GitHub Desktop.
Input validation with patterns
<!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,
pos;
myRegTest = new RegExp('^' + $regexp.val() + '+$', '');
myRegMatch = new RegExp('^' + $regexp.val() + '+', '');
value = new String($input.val());
if(myRegTest.test(value)) {
$valid.html('True');
$errormsg.html('');
$input.addClass('valid');
return true;
}
match = value.match(myRegMatch);
pos = (match === null) ? 0 : match[0].length;
bad = value.charAt(pos);
$valid.html('False');
$errormsg.html('First Bad Character: ' + bad);
$input.addClass('invalid');
return false;
});
function testlog(line) {
var line =$('<p></p>').append(line);
$('#output').prepend(line);
}
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment