I’m trying to restrict single and double quotations within the text box of a form ( ” or ‘). I’ve researched and seen JS to only allow alphanumeric and so on, but nothing to restrict a specific character exactly.
I’m fine with it not allowing it to be typed or to use an alert pop-up upon validation. Both work for me.
See code Below:
function validateForm() {
let x = document.forms["commentform"]["commentbox"].value;
if (x == "") {
alert("form must be filled out");
return false;
}
}<div align="center">
<h2>Comment Expiration Demand</h2>
<form name="commentform" action="/action_page.php" onsubmit="return validateForm()" method="post">
<input type="text" size="50" maxlength="40" name="commentbox" id="commentbox">
<br> 40 characters max length, no single or double quotations ( " or ' )
<br>
<br>
<input type="submit" value="submit" id="submit">
</form>
</div>Advertisement
Answer
First you are directly comparing the value of the input field. Instead you want to search for a string in that value.
Also, "" is an empty string. You need to use "'" for ' and '"' for ".
function validateForm() {
let x = document.forms["commentform"]["commentbox"].value;
if (x.indexOf("'") > -1 || x.indexOf('"') > -1) {
alert("form must be filled out");
return false;
}
}<body>
<div align="center">
<h2>Comment Expiration Demand</h2>
<form name="commentform" action="/action_page.php" onsubmit="return validateForm()" method="post">
<input type="text" size="50" maxlength="40" name="commentbox" id="commentbox">
<br>
40 characters max length, no single or double quotations ( " or ' )
<br>
<br>
<input type="submit" value="submit" id="submit">
</form>
</div>
</body>