简体   繁体   English

如何使用正则表达式替换cshtml文件中textareafor()中的特殊字符?

[英]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. 我必须从用户那里获得一条消息,该消息不应包含任何特殊字符。为此我分配了一个ID。

@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. 如图所示,我在onclick事件的函数中使用了前面提到的ID“ msg”。

<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() : 在同一个cshtml文件的开头,我还提到了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): 您应该编辑textarea的值-不确定您要传递给onclick的消息是什么,但是可以尝试这样做(也可以从点击中删除返回值):

 <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: 或者您可以通过将onkeyup绑定到textarea来验证用户何时输入:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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