Created
August 10, 2012 20:07
-
-
Save keriati/3317440 to your computer and use it in GitHub Desktop.
Input validation with patterns
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode 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, | |
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