如何限制文本框中的特定字符?

时间:2021-07-30 19:43:44

标签: javascript html

我试图限制表单文本框中的单引号和双引号(" 或 ')。我研究并看到 JS 只允许使用字母数字等,但没有完全限制特定字符。

我同意它不允许输入或在验证时使用警报弹出窗口。两者都适合我。

见下面的代码:

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>

2 个答案:

答案 0 :(得分:1)

首先,您直接比较输入字段的值。相反,您想在该值中搜索字符串。

另外,"" 是一个空字符串。您需要对 "'" 使用 ',对 '"' 使用 "

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>

答案 1 :(得分:0)

您可以创建一个 on input 事件以防止输入 [" , '] 并且如果输入警报将弹出并且输入框将被清空并创建一个空数组并添加其中添加的每个字符然后检查数组是否包含 [ " 或 '] 如果这样清空文本框并显示警报

var input = document.querySelector("#commentbox");

input.addEventListener("input", (e) => {
  //SAVE THE INPUT VALUE
  ele = e.target.value;
  //CREATE EMPTY ARRAY
  var charArr = [];
  //MAP THROUGH THE INPUT VALUE AND ADD EVERY CHAR INTO THE EMPTY ARRAY
  for (let i = 0; i < ele.length; i++) {
    charArr.push(ele[i]);
  }
  //IF THE ARRAY CONTAINS YOU RISTRICTED CHARS SHOW AN ALERT AND EMPTY THE INPUT BOX
  if (charArr.includes(`"`) || charArr.includes(`'`)) {
    alert(`Can not Put ( " , ' ) as an input`);
    e.target.value = "";
  } else {
    //DO YOUR FUNCTION
  }
});
<div>
  <h2>Comment Expiration Demand</h2>
  <form name="commentform" action="/action_page.php" onsubmit="returnvalidateForm()" 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>