Skip to content

Instantly share code, notes, and snippets.

@sigilioso
Created October 2, 2012 22:44
Show Gist options
  • Save sigilioso/3823794 to your computer and use it in GitHub Desktop.
Save sigilioso/3823794 to your computer and use it in GitHub Desktop.
jQuery simple input help to choose a correct value.
<html>
<head>
<style>
.input_error {
color: red;
font-weight: bold;
}
#code_value_error {
color: red;
}
</style>
</head>
<body>
<h1>Simple input validation on change</h1>
<p>Code can not be exists and just can contain letters, numbers or underscores.</p>
<p>Existent values:<span>code, special_code, special_code2</span>.</p>
<input id="code_value" /><div id="code_value_error"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
var existent = $('span').text().split(', ');
var invalid = new RegExp('[^A-Za-z0-9_]');
var check_input = function () {
var $input = $(this);
var value = $input.val();
if (($.inArray(value, existent) != -1) || invalid.test(value)) {
$input.attr('class', 'input_error');
$('#code_value_error').text('Invalid value');
}
else {
$input.attr('class', '');
$('#code_value_error').text('');
}
}
$('input').blur(check_input);
$('input').keyup(check_input);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment