I'm building a site with Visual Web Developer with C# and HTML.
I have a page where users can write feedback about my site in a textarea tag and then submit (in the textarea they can do a line-break everywhere).
The problem is that when I get back the text they wrote it appears without the linebreaks, for example:
if the user wrote:
"Hello, my name is
Omer N."
When I get it back it will look like this: "Hello, my name is Omer N.".
How can I fix this problem?
Depends on how you are storing the values. Remember that HTML and general input from fields following the whitespace rule, it will truncate/condense white space into a single entity.
So "Wide String" = "Wide String" and:
"Multi-line
string
here" will be truncated to "Multi-line string here" as you have experienced.
This is the default behavior.
So to keep your line breaks, spacing, etc.. you need to escape it or a process of encoding and decoding, before storing it.
It is explained here:
Many newcomers to web development cannot get their head around why the
carriage returns they made in their data on input from a textarea, or from a
text file, Excel spreadsheet etc. do not appear when the web page renders.
The solution is fairly obvious once the newcomer realizes that a web
page is only the browser's interpretation of html markup, and that a
new line in html is represented by the tag. So what is needed
is a way to swap carriage returns or line feeds with the tag.
Well, a way to Replace() them, actually.
<%# Eval("MyMultiLineValue").ToString().Replace(<linebreak>,"<br />") %>
The string.Replace() method allows this, but we also need to identify
what we want to replace with the html tag. How is a new line
represented in C# or VB.Net?
In C#, it's "\r\n", while in VB.Net, it's vbcrlf. However, there is
also a language independent option that does just the same thing:
Environment.NewLine.
<%# Eval("MyMultiLineValue").ToString().Replace(Environment.NewLine,"<br />") %>
Hope this helps! :)
Related
In ReactJS, how is it possible to render carriage returns that may be submitted by the user in a textarea control. The content containing the carriage returns is retrieved by an Ajax call which calls an API that needs to convert the \r\n characters to <br> or something else. And then, I have a div element in which the content should be rendered. I tried the following Ajax responses:
{
"Comment" : "Some stuff followed by line breaks<br/><br/><br/><br/>And more stuff.",
}
and
{
"Comment" : "Some stuff followed by line breaks\n\n\nAnd more stuff.",
}
But instead of rendering the carriage returns in the browser, it renders the br tags as plain text in the first case and \n character as space in the second case.
What's the recommended approach here? I'm guessing I should steer clear of the scary dangerouslySetInnerHTML property? For example the following would actually work but there must a safer way of handling carriage returns:
<div className="comment-text" dangerouslySetInnerHTML={{__html: comment.Comment}}></div>
dangerouslySetInnerHTML is what you want. The name is meant to be scary, because using it presents a risk for XSS attacks, but essentially it's just a reminder that you need to sanitize user inputs (which you should do anyway!)
To see an XSS attack in action while using dangerouslySetInnerHTML, try having a user save a comment whose text is:
Just an innocent comment.... <script>alert("XSS!!!")</script>
You might be surprised to see that this comment will actually create the alert popup. An even more malicious user might insert JS to download a virus when anyone views their comment. We obviously can't allow that.
But protecting against XSS is pretty simple. Sanitization needs to be done server side, but there are plenty of packages available that do this exact task for any conceivable serverside setup.
Here's an example of a good package for Rails, for example: https://github.com/rgrove/sanitize
Just be sure whichever sanitizer you pick uses a "whitelist" sanitization method, not a "blacklist" one.
If you're using DOM, ensure you're using innerHTML to add text. However, in react world, more favourable is to use https://www.npmjs.com/package/html-to-react
Also, browser only understands HTML and won't interpret \n as line break. You should replace that with <br/> before rendering.
my application was developed in asp.net mvc 4. we have list of jobs.
now we have allowed all special characters in job name, but
</ characters causes issue in creating <a> anchor tag. I have also tried to create anchor tag with these character on w3schools.com example. I noticed the same thing.
for example, job name => Test </ Test
but it will render ONLY "Test" NOT "Test </ Test".
We are creating this link in "fnRowCallback" using javascript as it is listing of jobs and for that we have used jquery datatable http://legacy.datatables.net/.
Please help me, how to prevent the characters using regular expression on JobName model property.
Thanks in advance.
If you mean for the display part of the anchor tag, everything should be fine - you should be getting ASP.NET MVC to perform any escaping required to represent your text properly in HTML, e.g. using #Html.AnchorLink(...). It's far better to be able to escape everything than to have to restrict your input :)
In general, raw data should never be written directly to the HTML - it can represent a huge security risk, for example. It should always be handled with the appropriate escaping, which should almost always be performed by the web presentation framework you're using rather than by any hand-crafted code.
I've just installed CKeditor rich text WYSIWYG editor on a site I'm building and it seems to be working ok except for the fact that it inserts text into my mysql database as encoded html rather than regular html and then when the browser outputs this text it converts the encoded data into regular html that then displays in the browser showing the html tags and none of the styling!?
eg I type:
"This is text"
into the editor and it then inserts
<p>This is text</p>
into the database. Then when the page is called the browser converts the above and outouts the following on the page:
<p>This is text</p>
obviously I just want "This is text" to display on the page.
Does anyone know why this is happening/how to solve it please?
Any suggestions would be most welcome.
Cheers
If you don't want CKEditor to create paragraphs for you, set config.autoParagraph to false. Additionally you may want to change enter key behaviour with config.enterMode set to CKEDITOR.ENTER_BR.
And regarding disappearing styles...
EDIT: OK, it seems I missed your point.
So your website is displaying HTML markup instead of HTML while rendering out what you typed?
Then the problem is your server side rather than CKEditor. You can verify in your console that CKEDITOR.instances.yourInstance.getData() yields the correct, unescaped HTML:
<p>This is text</p> // Right!
If it is so, and I strongly believe it is, CKEditor's just fine and this is your server app that is converting special chars into entities (i.e. like PHP htmlspecialchars) while saving to database. You didn't mention what kind of framework/language you use there, so I can just tell you that it is to secure user input to prevent cross-site scripting, breaking layouts etc. and all popular frameworks allow you to disable that feature for a particular field. Simply refer to documentation.
Modern templating languages tend to autoescape html input. For example, in DTL it would be displayed correctly in the template by simply using
{{ object.field_name|safe }}
This is a desired action, since user input is considered untrusted and may be considered malicious.
The browser is not parsing HTML, so on the page displaying (or in the php file) try using {! !} instead of {{ }}.
If you are using laravel, then you should use {!! $variable !!}.
For Laravel 7, 8, and 9 - foreaxample if there is a varable called- $student
and student varable holds "This is Text" in paragraph you must call the varable using singla culy brace front and back, inside two
I've got an ASP multiline textbox that saves user defined text to a database. When I retrieve the data, I serialize it into xml and then run it through an XSL transform to output my HTML.
Within my transform, I am passing the textbox defined data into a javascript function via an onclick event of an element.
The problem I'm running into...when a user enters a carriage return into the textbox and saves it to the database, a javascript error is generated on page load.
I'm using .NET's XslCompiledTransform to do the transform. There is a property on XmlDocument called PreserveWhiteSpace, default is false, that can be set to strip out white space in the XML. This solves the problem of not allowing a user to enter breaking text, however, the client wants to preserve the formatting of the text that they enter if at all possible.
From what I know, .NET XslCompiledTransform transforms carriage returns-new line into
. I believe these are the characters that are breaking the javascript.
My first thought was to strip out the carriage returns within the xsl prior to passing the string into the javascript function, but I've not been able to figure out what characters to "search" the string for.
I guess another question is what characters get stored in SQL for carriage returns from within an ASP.NET textbox control?
Looking directly at the data in the database, SQL seems to display the character as "non-displayable" characters or (2 empty boxes).
Has anyone had any experience with this type of thing?
I was able to do this in the code behind to get my desired results:
using (StringWriter sWriter = new StringWriter())
{
xTrans.Transform(xDoc, xslArgs, sWriter);
return sWriter.ToString().Replace("
", "\\r\\n");
}
One other thing that I've stumbled across...
Initially, I wanted to find a solution to this problem that did not require a "compiled" code change, ie. a way to do this within xsl aka "a short term fix".
I tried this first and was not successful...
<xsl:variable name="comment" select="normalize-space(.\Comment)" />
This essentially did nothing and I was still receiving the javascript error.
Eventually, I tried this...
<div onclick="Show('{normalize-space($comment)}'"></div>
The second actually worked in stripping out the white space, thus, the javascript error was avoided. This wasn't a complete solution for my requirements because it only solved the issue of the javascript error, however, it would effectively prevent the user from "breaking" the page.
For that reason, it could suffice as a short term solution.
I have a Perl program that is reading html tags from a text file. (im pretty sure this is working because when i run the perl program on the command line it prints out the HTML like it should be.)
I then pass that "html" to the web page as the return to an ajax request. I then use innerHTML to stick that string into a div.
Heres the problem:
all the text information is getting to where it needs to be. but the "<" ">" and "/" are getting stripped.
any one know the answer to this?
The question is a bit unclear to me without some code and data examples, but if it is what it vaguely sounds like, you may need to HTML-encode your text (e.g. using HTML::Entities).
I'm kind of surprized that's an issue with inserting into innerHTML, but without specific example, that's the first thing which comes to mind
There could be a mod on the server that is removing special characters. Are you running Apache? (I doubt this is what's happening).
If something is being stripped on the client-side, it is most likely in the response handler portion of the AJAX call. Show your code where you stick the string in the div.