javascript validation with regular expression not working - javascript

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.

Try to get the result in txt ie, get the value of replaced text inside your variable.
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.

Related

escaping/encoding characters ready for use in an attribute

Context:
I want to pass a title field into an Angular attribute. The title field is sometimes crazy with the characters people put in.
I have the following Csharp property:
Model.StoryTitle = "!"£$%^&*()<>;><~andanythingelsethatisweird";
<my-directive-thing story-title="#Model.StoryTitle"></my-directive-thing>
I also have this on a page that pulls the same field out of an Ajax call and gets populated by Kendo (darn legacy frameworks):
<my-directive-thing story-title="#= storyTitle #"></my-directive-thing>
On my directive side, I have the following code:
var storyTitle = $attrs.storyTitle || "";
Issue:
Due to the issue of having weird characters sometimes, I decided to escape it on the javascript side:
<my-directive-thing story-title="#= escape(storyTitle) #"></my-directive-thing>
The job was then easy as I put an unescape in the directive:
var storyTitle = unescape($attrs.storyTitle) || "";
Then everything works fine.
However, I don't know an equivalent for the Csharp.
Question:
Is there a trick I'm missing on the JavaScript + Csharp way of making sure ugly characters don't break attributes?
Escape those characters or transform those characters to HTML enteties. You should not do that on your client side. Your backend should deliver nice encoded/decoded data.
Model.StoryTitle = HttpUtility.HtmlDecode("!"£$%^&*()<>;><~andanythingelsethatisweird");
> HttpUtility.HtmlDecode() documentation

Prevent user from pasting line break

I'm currently having an issue with a code. In my code, I've got a textarea where the user can enter the title of an article and I would like this article to be only in one row. That's why I wrote a script to prevent users to press the return key. But they could bypass this security, indeed if they copy/past the line break they could enter a line break. So, is there a way to detect line break ? I suppose we can do this with regular expressions and with \n or \n. However I tried this:
var enteredText = $('textarea[name="titleIdea"]').val();
var match = /\r|\n/.exec(enteredText);
if (match) {
alert('working');
}
and it doesn't work for an unknown reason. I think the var enteredText = $('textarea[name="titleIdea"]').val(); doesn't work because when I try to alert() it, it shows nothing. But something strange is that when I do an alert on $('textarea[name="titleIdea"]').val(); and not on the enteredText variable it shows the content.
Have a great day. (sorry for mistakes, I'm french)
if they copy/past the line break they could enter a line break
That's why you shouldn't even worry about preventing them from entering it - just don't save it. Remove it on the blur and input events if you really want to, but the only time it actually matters is before you save it to the database (or whatever you are using).
$('textarea[name="titleIdea"]').on('blur input', function() {
$(this).val($(this).val().replace(/(\r\n|\n|\r)/gm,""));
});
And, as other people have already mentioned, if they can't do line breaks, you shouldn't be using a textarea.
I assume your problem is with the paste event.
If i guessed this is my snippet:
$(function () {
$('textarea[name="titleIdea"]').on('paste', function(e) {
var data;
if (window.clipboardData) { // for IE
data = window.clipboardData.getData('Text');
} else {
data = e.originalEvent.clipboardData.getData('Text');
}
var match = /\r|\n/.exec(data);
if (match) {
alert('working');
console.log(data);
}
})
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<textarea name="titleIdea">
</textarea>
This needs to be handled in the backend. Even if you use the recommended appropriate HTML input type of text (instead of textarea), you still do not remove the possibility of return chars getting saved.
The two other answers use Javascript - which technically is the domain of this question. However, this can not be solved with Javascript! This assumes that the input will always come from the form you created with the JS function working perfectly.
The only way to avoid specific characters being inserted into your database is to parse and clean the data in the backend language prior to inserting into your database.
For example, if you are using PHP, you could run a similar regex that stripped out the \n\r chars before it went into processing.
Javascript only helps the UX in this case (the user sees what they will be saving). But the only way to ensure you have data integrity is to validate it on the server side.

Pull bean value as String for Javascript use

I'm trying to set a component's text based on a bean's value. I'm using jquery for this because the text changes depending on certain conditions.
So, the jquery code looks like this:
window.onload =function(){
$('.pnx-inline-input').on("change keyup paste", function(){
var saveText = #{extra.Active_Save};
$('.save-button .pnx-btn-text').html(saveText);
});
The Extra bean handles the localization. So, let's say that the locale is France, and the text is Enregister. The thing is that when rendered the page, the code segment looks like this
window.onload =function(){
$('.pnx-inline-input').on("change keyup paste", function(){
var saveText = Enregister;
$('.save-button .pnx-btn-text').html(saveText);
});
Of course, Enregister is not defined anywhere, and this causes an error. I need to have to code look like
var saveText = "Enregister";
for this to make sense.
How can I make this happen? Thanks!
JSF is in the context of this question merely a HTML code generator. Just write down those quotes yourself in the HTML template. They are part of generated HTML output, not of the Java variable. You know, JavaScript doesn't run together with Java/JSF (i.e. it's not server side). Instead, it runs together with HTML (i.e. it's client side).
var saveText = "#{extra.Active_Save}";
Note that you still need to take into account that the value is properly JS-escaped, otherwise the whole thing would still break in JavaScript side if the string itself contains doublequotes or other special characters in JS such as newlines. The JSF utility library OmniFaces has an EL function for the very purpose, the #{of:escapeJS()}:
var saveText = "#{of:escapeJS(extra.Active_Save)}";
You can of course also homegrow your own based on e.g. Apache Commons Lang StringEscapeUtils.

saving value from form doesn't work

So, storing a Java String into a form hidden input value. I call said value via javascript and attempt to store it into a var. Strangely, I can display the value via alert but javascript crashes when I try to save it into a var.
The first line is from the initializing jsp file. It does some stuff that gets the string. The string is a list of ints that I plan on splitting in javascript for some stuff.
"<form id = \"listArrForm\"> <input id = \"listArr\" value = "+ output +" type = \"hidden\"></form>"
var listArr = document.getElementById("listArr").value; //Does work
alert(document.getElementById("listArr").value); //Does work
So yea, I'm guessing it has to do with the the type of value being retrieved?
Well, both should work as you can see in this jsfiddle: http://jsfiddle.net/2eWja/
What are you storing in the value that makes the script not work? Are you sure you're not putting quotes in?
what browser are you using? There could be problem for some
Btw using getElementById is known to be wrong. ;)

javascript conversion from html code to real value

I have a textbox and i have values in database like ® which is equal to ® .I fetch data and write it into textbox but it writes the data as it is.The code part is like this
var data=database_values;//here there is data like this "DOLBY®"
document.getElementById(id).value = data;
I want to make the textbox value DOLBY® not DOLBY®
If you are getting ® as ® then unescape it.
document.getElementById(id).value = unescape(data);
Assuming you're using a server side language (i.e php) there are functions for that.
for example this will work with php:
html_entity_decode($data);
if you're set on using javascript, there's still a way.
see the code here.
Hi i found a way to unescape html code.Here is the function
function unescapeHTML(html) {
var tempHtmlNode = document.createElement("tempDiv");
tempHtmlNode.innerHTML = html;
if(tempHtmlNode.innerText)
return tempHtmlNode.innerText; // IE
return tempHtmlNode.textContent; // FF
}
Thanks for your help anyway

Categories