简体   繁体   中英

javascript validation with regular expression not working

In my asp.net web application. 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

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.

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? 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.

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.

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