1

I'm trying to prevent users from inputting and submitting single quotes ( ' ) into the textarea. below is what I have, but it isn't work.

    <script>
    function valtxtarea() {
        var val = document.getElementById('textarea').value;

        if ('\''.test(val)) {
            alert('do not add single qoutes to your inputs!');
        }
    }

</script>

<form>
    enter text below
    <textarea>input contents here</textarea>
    <input type="button" onclick="valtxtarea();" value="send">
</form>
2
  • stackoverflow.com/questions/2521559/validation-of-textarea Commented Jan 29, 2016 at 12:39
  • .test is for regular expressions what you have is a string, did you mean to do /'/.test(val). You should have been getting a .test is not a function or similar error on your browser's developer tools console Commented Jan 29, 2016 at 12:43

3 Answers 3

3

You missed the id attribute as well as the regex isn't valid

function valtxtarea() {
  var val = document.getElementById('textarea').value;

  if (/\'/.test(val)) {
    alert('do not add single qoutes to your inputs!');
  }
}
<form>
  enter text below
  <textarea id="textarea"></textarea>
  <input type="button" onclick="valtxtarea();" value="send">
</form>

Sign up to request clarification or add additional context in comments.

2 Comments

How do I add other characters like ),(,%. A link to a tutorial if any will be fine.
u need to check regex tutorials
1

Better yet, why not prevent them from even typing it?

  <form>
  enter text below
  <textarea id='inputText' oninput="valtxtarea();"></textarea>
  <input type="button" value="send">
  </form>

  <script>
  var oldValue = "input contents here";
  document.getElementById('inputText').value = oldValue;
  function valtxtarea() {
    var textArea = document.getElementById('inputText');
    if (textArea.value.match(/.*\'.*/g)) {
        textArea.value = oldValue;
    } else {
      oldValue = textArea.value;
    }
  }
  </script>

With this every time they type a char it is check and if it contains a ' then it sets it back to the old value. You could easily expand it to include other characters you do not want to allow.

Comments

0
var val = document.getElementById('textarea').value;

There is no HTML element with the id textarea.

Do something like this:

<textarea id="textarea">input contents here</textarea>

Also you probably want to prevent form submission if there is a validation error, so put return false; in the if in valtxtarea() and put return valtxtarea() in the onclick.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.