In a form I use an input field to rename a filename. How can I prevent the use of / and . ?? All letters and numbers are ok. I tried with pattern="" but don't know what to put there...
            Asked
            
        
        
            Active
            
        
            Viewed 459 times
        
    -2
            
            
        - 
                    pattern is not prevent them, it will throw an error when you try to submit. – epascarello May 18 '20 at 14:08
- 
                    Does this answer your question? [restrict a character to type in a text box](https://stackoverflow.com/questions/3059559/restrict-a-character-to-type-in-a-text-box) – Clyde Lobo May 18 '20 at 14:09
- 
                    [The Great Escapism (Or: What You Need To Know To Work With Text Within Text)](http://kunststube.net/escapism/) — Don't fight it, just *encode* whatever input you receive correctly. In the case of file paths, you may want to *replace* special characters with underscores for example. But really, accepting any input and using it on *actual file paths* is a read flag; you should probably just store those in a database and use your own file names for the actual files on disk. – deceze May 18 '20 at 14:10
- 
                    And trying to prevent the input in an HTML widget is pointless, this requires *server side validation* at the very least. – deceze May 18 '20 at 14:11
- 
                    You may want to check this question as it covers multiple excellent methods for doing this with Javascript: https://stackoverflow.com/questions/5582574/how-to-check-if-a-string-contains-text-from-an-array-of-substrings-in-javascript – David Scott May 18 '20 at 14:12
2 Answers
-1
            
            
        If using jquery, then below code will allow only alphanumeric values
$('#yourInputTag').bind('keyup', function(e) {
        $(this).val($(this).val().replace(/[^0-9a-zA-Z]/g, ''));
        if (e.which >= 97 && e.which <= 122) {
            var newKey = e.which - 32;
            e.keyCode = newKey;
            e.charCode = newKey;
        }
        $(this).val(($(this).val()));
    });
 
    
    
        Satinder singh
        
- 10,100
- 16
- 60
- 102
-1
            
            
        You can bind a onkeyup function with your input which will fire everytime a key is pressed and replace your input value there.
<html>
<input type="text" placeholder="enter value" onkeyup="checkValueWithRegex()" id="myInput">
<script>
function checkValueWithRegex() {
  var value = document.getElementById("myInput").value;
  value = value.replace(/[^a-zA-Z0-9]/g, '');
  document.getElementById("myInput").value = value;
}
</script>
</html>
 
    
    
        Aman Kumayu
        
- 381
- 1
- 9
