Sunday, April 23, 2017

JQuery code to restrict form entries to alphanumeric and force lowercase to uppercase

I've come up with a JavaScript/JQuery code that restricts form input entries to alphanumeric and at the same time forces lowercase letter entries to uppercase entries. Users entering the form may only type letters and numbers but when they type lower case letters, the entry gets converted to uppercase. The HTML code is listed below. A form with with ID "input-toupper" is where the user will type in their entry. The javaScript on script.js will restrict the entry to letters and numerals. But when a lowwercase letter is entered, it gets converted to uppercase.
<!DOCTYPE html>
<html>
<head>
 <title>Restrict enter and force lower to upper</title>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
 <script type="text/javascript" src="script.js"></script>
</head>
<body>
<form>
 <!--restricts entry to alpha number and forces lowercae to uppercase-->
 <input id="input-toupper" type="text">
</form>
</body>
</html>

The JavaScript contains the JQUery code for make this happen. The keydown event for the input checks against the regex to see if the character typed in is a letter or numeral. If the character entry does not match the regex, the entry is prevented on the input.
$(document).ready(function(){

 $('input#input-toupper').on('keypress',function(event){
  var regex=new RegExp("^[a-zA-Z0-9]+$");
  var key=String.fromCharCode(!event.charCode?event.which:event.charCode);
  if(!regex.test(key)){
   event.preventDefault();
   return false;
  }
 });
 
 $('input#input-toupper').on('keyup',function(){
  
  var toupper=$(this).val().toUpperCase();
  $(this).val(toupper);
 })
})

The jsfiddle link to the codes can be found here, https://jsfiddle.net/jundolor/sm0jjopm/

No comments:

Post a Comment