0

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.

2
  • 1
    assign the result back to txt Commented Dec 17, 2015 at 7:36
  • 1
    the replace() method returns a copy of the string with the replacement applied. It does not modify the original string in the txt variable. Commented Dec 17, 2015 at 8:07

3 Answers 3

1

Try to get the result in txt ie, get the value of replaced text inside your variable.

txt = txt.replace(/[\\\/:*>"<>|]/g, '');
Sign up to request clarification or add additional context in comments.

Comments

1

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;
}

Comments

0

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.

1 Comment

It is not like that.. I validate it in the clientside. Instead of doing it after the form submit. I need it right at the time the user input some value in the text box.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.