Skip to content

Instantly share code, notes, and snippets.

@yashasvi9199
Created June 6, 2023 07:06
Show Gist options
  • Save yashasvi9199/2639ae175ab18f39f288acff8625d73c to your computer and use it in GitHub Desktop.
Save yashasvi9199/2639ae175ab18f39f288acff8625d73c to your computer and use it in GitHub Desktop.
Restrict special character and space in Input field
function userValidation(val,event) {
var k = event ? event.which : window.event.keyCode;
var len = val.length;
if (len == 0 && k == 32){
return false;
}
//Restrict spacial character
// 45 = hyphen (-), 46 = fulls top (.), 95 = underscore (_), 48-57 = 0-9, 65-90 = Uppercase alphabets 97-122 = Lowercase alphabets
if (!((k >= 48 && k <= 57) || (k >= 65 && k <= 90) || (k >= 97 && k <= 122) || k == 46 || k == 45 || k == 95 || k == 32)) {
return false;
}
//Reducing the length by 1 to get previously entered input
//This will restrict user from entering multiple spaces
len--;
if(val.charAt(len) == " " && k == 32){
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment