1

I have to get a Message from the user which should not include any special characters.I assigned an id to this.

@Html.TextAreaFor(model => model.Message, new { id= "msg", htmlAttributes = new { @class = "form-control" } })

On clicking the Submit button, the message is sent. I use the previously mentioned id "msg" in the function of onclick event, as shown.

<input type="submit" value="Contact Us" class="btn btn-default" id="submit" onclick="return removeSpecialChar(msg)"/>

At the beginning of the same cshtml file, I also mentioned the function removeSpecialChar():

<SCRIPT type=text/javascript>
    function removeSpecialChar(msg) {
        msg = msg.replace(/[^\w\s]/gi, '');
        return msg;
    }
</SCRIPT>

However, the special characters are not being replaced in the message. Please help me in understanding the issue with this approach and how to resolve this? Also, suggest if it is necessary to use the namespace for regex?

Pete
  • 57,112
  • 28
  • 117
  • 166
  • You do not have any value in `msg` in `onclick="return removeSpecialChar(msg)"`. Check https://stackoverflow.com/questions/5453937/onclick-event-not-working-in-javascript and https://stackoverflow.com/questions/4268085/the-current-element-as-its-event-function-param – Wiktor Stribiżew Nov 26 '18 at 13:56
  • That is, try `onclick="removeSpecialChar(this)"` and then `return msg.value.replace(/[^\w\s]/gi, '');` – Wiktor Stribiżew Nov 26 '18 at 14:02
  • @WiktorStribiżew I want to get the value in msg from the TextArea provided for the message, so that it's passed to the onclick function. Maybe I am not using the msg correctly as it's the id. Can you please suggest how to get the value of message? – Aakanksha Singh Nov 26 '18 at 14:06
  • If you mean to pass another element value, do it: `removeSpecialChar(document.getElementById('msg').value)` – Wiktor Stribiżew Nov 26 '18 at 14:10
  • @WiktorStribiżew Thanks for the suggestion, this makes sense. But when I am defining the function removeSpecialChar(?), what should I be passing as the argument there? It cannot be msg. – Aakanksha Singh Nov 26 '18 at 14:16

1 Answers1

1

You should edit the value of the textarea - not sure what msg is you pass into the onclick but try this (also removed the return from the click):

<SCRIPT type=text/javascript>
  function removeSpecialChar() {
    var msg = document.getElementById('msg');
    msg.value = msg.value.replace(/[^\w\s]/gi, '');
  }
</SCRIPT>
<textarea id="msg"></textarea>
<input type="submit" value="Contact Us" class="btn btn-default" id="submit" onclick="removeSpecialChar()"/>

Or you could validate when the user is typing by binding an onkeyup to the textarea:

<SCRIPT type=text/javascript>
  function removeSpecialChar(input) {
    input.value = input.value.replace(/[^\w\s]/gi, '');
  }
</SCRIPT>
<textarea id="msg" onkeyup="removeSpecialChar(this);"></textarea>
Pete
  • 57,112
  • 28
  • 117
  • 166