Basically I don't want a user to input the following: (!@#$%^&*()_ []{}';:".<>?) given that this is my code:
<div class = "form-item">
<label for = "Name">Name: </label>
<input type = "text" id = "Name" name="Cname">
</div>
how do i do this? hopefully you can do it using the code given
We tried the regex on JavaScript but to be honest i don't understand it.
CodePudding user response:
you don't really need regex. Just create a string of your special characters and loop through them each time the input is changed
var sc = "(!@#$%^&*()_ []{}';:\".<>?)"
function test() {
let input = document.getElementById('Name').value
let last = input.substring(input.length - 1, input.length)
for (i = 0; i < sc.length; i ) {
if (last == sc.substring(i, i 1)) document.getElementById('Name').value = input.substring(0, input.length - 1)
}
}
<div >
<label for="Name">Name: </label>
<input type="text" id="Name" name="Cname" oninput="test()">
</div>
CodePudding user response:
You can copy the script below to your javascript file or place the script inside the html like the code below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
input {
width: 250px;
padding: 4px 10px;
font-size: 16px;
}
</style>
</head>
<body>
<input type="text" placeholder="type" />
<script>
// This will prevent special character and allow only a-z A-Z 0-9 and space
document.querySelector('input').addEventListener('keypress', function (e) {
// [^a-zA-Z0-9 ] means anything except a-z A-Z 0-9 and space
var regex = new RegExp("^[a-zA-Z0-9 ] $");
// if keypress is not a-z A-Z 0-9 and space then prevent it
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
});
</script>
</body>
</html>