简体   繁体   中英

How to replace special characters in a textareafor() in a cshtml file using regex?

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?

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM