简体   繁体   English

正则表达式的javascript验证不起作用

[英]javascript validation with regular expression not working

In my asp.net web application. 在我的asp.net Web应用程序中。 I need to validate a textbox entry to avoid these special characters \\/:*>"<>| .I planned to replace the character with empty string, and for that wrote a javascript function and addded the attribute to call the function from server side as below 我需要验证文本框条目以避免这些特殊字符\\/:*>"<>| 。我计划用空字符串替换该字符,为此编写了一个javascript函数并添加了从服务器端调用该函数的属性如下

txtProjectName.Attributes.Add("onkeyup", "ValiateSpecialCharacter()");

As of this every thing is fine and the function is called.while enter any character. 因此,一切都很好,可以在输入任何字符的同时调用该函数。 The function is 该功能是

function ValiateSpecialCharacter(){
    var txt=document.getElementById("<%=txtProjectName.ClientID%>").value;
    txt.replace(/[\\\/:*>"<>|]/g, '');
    alert(txt);
    document.getElementById("<%=txtProjectName.ClientID%>").value=txt;
}

I use a regular expression in the function to do this. 我在函数中使用正则表达式来执行此操作。 But the test is not getting replaced as planned. 但是测试并没有按计划进行更换。 Is there any mistake in this code.Also note that the alert is working. 该代码中是否有任何错误。还请注意警报正在运行。

尝试以txt格式获取结果,即获取变量内替换文本的值。

txt = txt.replace(/[\\\/:*>"<>|]/g, '');

In your query you getting previous value.Assign properly like this txt = txt.replace(/[\\\\\\/:*>"<>|]/g, ''); .It show the latest result in alert box. 在您的查询中,您将获得以前的值。像这样txt = txt.replace(/[\\\\\\/:*>"<>|]/g, '');正确txt = txt.replace(/[\\\\\\/:*>"<>|]/g, '');它在alert框中显示最新结果。

function ValiateSpecialCharacter(){
var txt=document.getElementById("<%=txtProjectName.ClientID%>").value;
txt = txt.replace(/[\\\/:*>"<>|]/g, '');
alert(txt);
document.getElementById("<%=txtProjectName.ClientID%>").value=txt;
}

This is not what you asked, but seems like a strange way to go about your needs. 这不是您要的,但似乎是满足您需求的一种奇怪方法。 Unless, I misunderstood the question. 除非,我误解了这个问题。 Since you are running ASP.NET on the server, why use JavaScript for server validation? 由于您正在服务器上运行ASP.NET,为什么要使用JavaScript进行服务器验证? It usually does make sense to validate input on the client. 通常,验证客户端上的输入确实有意义。 For that, you need to hook an event like form submit to call the javascript function. 为此,您需要挂钩一个事件,例如表单提交,以调用javascript函数。

If you want to validate on the server, use something like, inside a function handling form submit: 如果要在服务器上进行验证,请在函数处理表单内部使用类似的方法提交:

Regex re = new Regex("^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\\.[a-zA-Z]{1,})+$");
if (!re.IsMatch (domain.Text)) {
    warningLabel.Text = "Domain format is invalid!";
    formError = true;
}

Obviously, you don't validate the domain so change the regex etc. No JavaScript is needed for server-side validation. 显然,您无需验证域,因此请更改正则表达式等。服务器端验证不需要JavaScript。

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

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