Bayar Shahab
Bayar Shahab

Reputation: 31

Disable special characters (quotation mark)

I have below code that disables special characters to be inserted into a text filed on HTML form.

It can be seen that the special characters that I need to disable are between quotation marks, while I need the quotation mark " itself to be disabled but I can not do that because if I add another quotation mark in the middle then it reads as it is the end of the first quotation.

How can I disable the quotation mark as well as a special character to be entered?

function disableSpecialChars() 
{ 
    var spclChars = ",!@#$%^&*()/"; // specify special characters 
    var content = document.getElementById("permanentaddress").value; 
    for (var i = 0; i < content.length; i++) 
    { 
        if (spclChars.indexOf(content.charAt(i)) != -1) 
        { 
            alert ("Special characters(,!@#$%^&*()) are not allowed."); 
            document.getElementById("permanentaddress").value = ""; 
            return false; 
        } 
    } 
}

Upvotes: 0

Views: 133

Answers (2)

Mgorunuch
Mgorunuch

Reputation: 686

Use regexp for this.

function check(value) {
  const regexp = new RegExp(/[,!@#$%^&*()\/"]/);
  return !regexp.test(value);
}

function validate() {
  const input = document.getElementById('my-input');
  const isValid = check(input.value);
  
  const resultDiv = document.getElementById('result');
  resultDiv.innerHTML = isValid ? 'Valid' : 'Not Valid';
}
<input id="my-input">
<button type="button" onclick="validate();">Validate</button>
<div id="result">
</div>

Upvotes: 1

akshaypjoshi
akshaypjoshi

Reputation: 1295

You need to use one backslash before Quotation mark(") like this :

 function disableSpecialChars()
{
    var spclChars = ",!@#$%^&*()/\""; // specify special characters 
    var content = document.getElementById("permanentaddress").value;
    for (var i = 0; i < content.length; i++)
    {
        if (spclChars.indexOf(content.charAt(i)) != -1)
        {
            alert ("Special characters(,!@#$%^&*()) are not allowed.");
            document.getElementById("permanentaddress").value = "";
            return false;
        }
    }
}

or you can use ASCII code for all special characters:

function disableSpecialChars(e) {
    var k;
    document.all ? k = e.keyCode : k = e.which;
    return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57));
}

Upvotes: 0

Related Questions