ColdFusion - How to output single quotes into a text field? - coldfusion

I am using ColdFusion 9.
I can't find a means to successfully output a single quote into a text field.
I create form fields using a CFSCRIPT user defined function. (I've minimized the options for the sake of simplicity for this example.)
When my output contains a single quote, the text field gets totally screwed up, be sure to run the example and view the HTML. I have tried using PreserveSingleQuotes() every conceivable way possible.
// USE EITHER STRING
MyString = "This string works fine.";
MyString = "This single quote's the problem!";
writeOutput(createInputBox(MyString));
// CREATE TEXT INPUT
function createInputBox(Value) {
LOCAL.Properties = " value='#preserveSingleQuotes(ARGUMENTS.Value)#'";
LOCAL.Item = "<input size='50' type='text' #LOCAL.Properties# />";
return LOCAL.Item;
}
Do you know of a solution?
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
ANSWER
Get rid of the preserveSingleQuotes() function, as it does nothing outside of a SQL block. (Thanks Adam!).
LOCAL.Properties = " value='#ARGUMENTS.Value#'";
Then, get rid of the single quotes and replaced with escaped double quotes:
LOCAL.Properties = " value=""#ARGUMENTS.Value#""";
This will still choke on strings like this though:
MyString = "This is my F##'''""$":""ing problem!";
So, add the htmlEditFormat() function like this:
LOCAL.Properties = " value=""#htmlEditFormat(ARGUMENTS.Value)#""";
Thanks for the help!!!

A single quote should not give you a problem in an attribute value in HTML, unless:
* you're not quoting the attribute values, eg:
<input value=#myvar#>
The solution here is to quote your attributes, eg:
<input value="#myvar#">
or
* you are quoting your attributes, but are using single quotes :
<input value='#myVar#'>
Will end up being:
<input value='value with a ' in it'>
This - of course is invalid mark-up: the browser sees the value as 'value with a ', and the rest of it is just garbage.
If you need to do this:
* switch to using double-quote delimiters
* use htmlEditFormat() around your variable value (this will escape embedded double-quotes).
To troubleshoot this sort of thing, ALWAYS look at the HTML source. This will help you work out what's going on.
NB: to everyone mentioning preserveSingleQuote(): this function does NOTHING outside of a CFQUERY block. So it's not going to help here.

The issue you're experiencing relates to the character delimiters for the value field. If you use single quotes as field delimiters, and a single quote is provided by your app, there will be a problem. One ways I've dealt with this in the past is to use double quotes for the field. The line shown below should plug into your code:
LOCAL.Properties = " value=""#preserveSingleQuotes(ARGUMENTS.Value)#""";
The approach shown by Sean Kimball is equally valid. Depending on the situation, I've used both approaches.
There was another comment re: preserveSingleQuotes. I can't say that I've used this outside of database calls, but if it works for you in this situation, I've learned something, too!

// CREATE TEXT INPUT
function createInputBox(Value) {
LOCAL.Properties = ' value="' &#preserveSingleQuotes(ARGUMENTS.Value)#& '"';
LOCAL.Item = '<input size="50" type="text" #LOCAL.Properties# />';
return LOCAL.Item;
}
// USE EITHER STRING
MyString = "This string works fine.";
MyString = "This single quote's the problem!";
writeOutput(createInputBox(MyString));

Related

HTML - Using pattern attribute

In html form, I need textarea which allows any type of text: numbers, symbols, newline or letters, including Hebrew letters. The only two rules:
The input must include the string: "{ser}"
The input should prohibit any use of "{" or "}" except for the above string
I tried this:
<form action="#">
...
<textarea pattern="[^\{\}]*\{ser\}[^\{\}]*" required>
האם אתה נמצא בשבת הקרובה? אם כן נא השב {ser} + שם מלא
</textarea>
...
<input type="submit" />
...
</form>
But for some reason it also allows sending texts that do not meet the rules. I would appreciate your help.
You cannot use pattern attribute on textareas, see the documentation.
maxlength specifies a maximum number of characters that the
is allowed to contain. You can also set a minimum length that is
considered valid using the minlength attribute, and specify that the
will not submit (and is invalid) if it is empty, using the
required attribute. This provides the with simple
validation, which is more basic than the other form elements (for
example, you can't provide specific regexs to validate the value
against using the pattern attribute, like you can with the input
element).
Perhaps implement a regex match with javascript?
function validateTextarea(text) {
var re = /ser/g;
var result = text.match(re);
if(result != null && result.length > 0)
// Do something
}
Then probably the best way is to check the function in onsubmit form attribute.

Hyperlinks inside object fields

I have an object inside my Ember app, with a description field. This description field may contain hyperlinks, like this
My fancy text <a href='http://other.site.com' target='_blank'>My link</a> My fancy text continues...
However, when i output it normally, like {{ description }} my hyperlinks are displayed as a plain text. Why is this happening and how can i fix this?
Handlebars escapes any HTML within output by default. For unescaped text in markup use triple-stashes:
{{{ description }}}
There's an alternative when one controls the property: Handlebars.SafeString. SafeStrings are assumed to be safe and are not escaped either. From the documentation:
Handlebars.registerHelper('link', function(text, url) {
text = Handlebars.Utils.escapeExpression(text);
url = Handlebars.Utils.escapeExpression(url);
var result = '' + text + '';
return new Handlebars.SafeString(result);
});
Note - please be careful with this. There are security concerns with rendering unescaped text that has come from user input; an attacker could inject a malicious script into the description and hijack your page, for example.

specify string in title while using groovy template for play 1.2.5

I am using the groovy template for play 1.2.5. I need to append a string to the title tag for the html page. However, the option I tried below does not result in the value to be displayed - I am wondering whether the issue is related to escaping or faulty logic on my part (which I'm quite capable of).
#{set title:'ABCD | ${object.property}' /} // object.property has a valid String value
Thanks in advance!
While setting the title, the title is already within the "#{}" tag. If passing another variable, one does not need to use the ${} format - simply ensure that you pass in the variable needed without the ${} and outside the '' characters. For instance:
#{set title:'ABCD | ' + object.property /}
This worked (as long as object.property is valid). Unless I am mistaken, you can also use the
object?.property format to avoid cases where the object might be null. Hope it helps!

Add a newline after each closing html tag in web2py

Original
I want to parse a string of html code and add newlines after closing tags + after the initial form tag. Here's the code so far. It's giving me an error in the "re.sub" line. I don't understand why the regex fails.
def user():
tags = "<form><label for=\"email_field\">Email:</label><input type=\"email\" name=\"email_field\"/><label for=\"password_field\">Password:</label><input type=\"password\" name=\"password_field\"/><input type=\"submit\" value=\"Login\"/></form>"
result = re.sub("(</.*?>)", "\1\n", tags)
return dict(form_code=result)
PS. I have a feeling this might not be the best way... but I still want to learn how to do this.
EDIT
I was missing "import re" from my default.py. Thanks ruakh for this.
import re
Now my page source code shows up like this (inspected in client browser). The actual page shows the form code as text, not as UI elements.
<form><label for="email_field">Email:</label>
<input type="email" name="email_field"/><label
for="password_field">Password:</label>
<input type="password" name="password_field"/><input
type="submit" value="Login"/></form>
EDIT 2
The form code is rendered as UI elements after adding XML() helper into default.py. Thanks Anthony for helping. Corrected line below:
return dict(form_code=XML(result))
FINAL EDIT
Fixing the regex I figured myself. This is not optimal solution but at least it works. The final code:
import re
def user():
tags = "<form><label for=\"email_field\">Email:</label><input type=\"email\" name=\"email_field\"/><label for=\"password_field\">Password:</label><input type=\"password\" name=\"password_field\"/><input type=\"submit\" value=\"Login\"/></form>"
tags = re.sub(r"(<form>)", r"<form>\n ", tags)
tags = re.sub(r"(</.*?>)", r"\1\n ", tags)
tags = re.sub(r"(/>)", r"/>\n ", tags)
tags = re.sub(r"( </form>)", r"</form>\n", tags)
return dict(form_code=XML(tags))
The only issue I see is that you need to change "\1\n" to r"\1\n" (using the "raw" string notation); otherwise \1 is interpreted as an octal escape (meaning the character U+0001). But that shouldn't give you an error, per se. What error-message are you getting?
By default, web2py escapes all text inserted in the view for security reasons. To avoid that, simply use the XML() helper, either in the controller:
return dict(form_code=XML(result))
or in the view:
{{=XML(form_code)}}
Don't do this unless the code is coming from a trusted source -- otherwise it could contain malicious Javascript.

This regex does not work in Chrome

Hi i just put up a validation function in jScript to validate filename in fileupload control[input type file]. The function seems to work fine in FF and sometimes in ie but never in Chrome. Basically the function tests if File name is atleast 1 char upto 25 characters long.Contains only valid characters,numbers [no spaces] and are of file types in the list. Could you throw some light on this
function validate(Uploadelem) {
var objRgx = new RegExp(/^[\w]{1,25}\.*\.(jpg|gif|png|jpeg|doc|docx|pdf|txt|rtf)$/);
objRgx.ignoreCase = true;
if (objRgx.test(Uploadelem.value)) {
document.getElementById('moreUploadsLink').style.display = 'block';
} else {
document.getElementById('moreUploadsLink').style.display = 'none';
}
}
EDIT:
Nope still does not seem to work , i am using IE 8(tried all the compatibility modes), Chrome v8.0, FF v 3.6.
Here is a html snippet in which i wired up the validate function,
<div>
<input type="file" name="attachment" id="attachment" onchange="validate(this)" />
<span class="none">Filename should be within (1-25) letters long. Can Contain only letters
& numbers</span>
<div id="moreUploads">
</div>
<div id="moreUploadsLink" style="display: none;">
Attach another File</div>
</div>
It works perfectly for me. How do you call the validate function ? – M42
You tried this on Google Chrome and IE 8 ? i added HTML Snippet in where in i used all of the recommended regX. No Clues as to why doesn't work!!
Mike, i am unable to comment your post here So this is for you.
The Validation Fails for which ever file i choose in the html input. I Also wired the validation in onblur event but proves same. The validate function will mimic the asp.net regular expression validator which displays validation error message when regular expression is not met.
Try simplifying your code.
function validate(Uploadelem) {
var objRgx = /^[\w]{1,25}\.+(jpg|gif|png|jpeg|doc|docx|pdf|txt|rtf)$/i;
if (objRgx.test(Uploadelem.value)) {
document.getElementById('moreUploadsLink').style.display = 'block';
} else {
document.getElementById('moreUploadsLink').style.display = 'none';
}
}
Your specification is hazy, but it appears that you want to allow dots within filenames (in addition to the dot that separates filename and extension).
In that case, try
var objRbx = /^[\w.]{1,25}\.(jpg|gif|png|jpeg|doc|docx|pdf|txt|rtf)$/i;
This allows filenames that consist only of the characters a-z, A-Z, 0-9, _ and ., followed by a required dot and one of the specified extensions.
As far as I know, Chrome adds a path in front of the filename entered, so you have just to change your regex from:
/^[\w]{1,25}\.*\.(jpg|gif|png|jpeg|doc|docx|pdf|txt|rtf)$/
to:
/\b[\w]{1,25}\.+(jpg|gif|png|jpeg|doc|docx|pdf|txt|rtf)$/
SOLVED
Primary reason that all [CORRECT regx pattern] did not work is Different browsers returned different values for HTML File Input control.
Firefox: Returns the File Upload controls FileName {As Expected}
Internet Explorer: Returns the Full Path to the File from Drive to File [Pain in the Ass]
Chrome: Returns a fake path as [C:\FakePath\Filename.extension]
I got a solution to the thing for chrome and FF but not IE.
Chrome and Firefox:
use FileUploadControlID.files[0].fileName or FileUploadControlID.files[0].name
IE
Again biggest pain in the ass [someone suggest a solution]
Valid Regex to Validate both fileName and Extension would be:
/\b([a-zA-Z0-9._/s]{3,50})(?=(\.((jpg)|(gif)|(jpeg)|(png))$))/i
1.File Nameshould be between 3 and 50 characters
2. Only jpg,gif,jpeg,png files are allowed