Validate file extensions in Apex - visualforce

End user can upload files in a Visualforce page. In the backend I need to create a list of allowed file extensions, and restrict the user to that list. How do I create the extensions list and validate it? Any help is very much appreciated.

You don't need apex for that?
<apex:inputFile> has accept parameter which you can use. Bear in mind this will check contentType, not extension (which is bit more proper way to do it).
If you still want the validation in apex - probably something like this?
String fileName = 'foobar.xls';
Set<String> acceptedExtensions = new Set<String> {'.doc','.txt', '.jpg'};
Boolean found = false;
for(String s : acceptedExtensions){
if(found = fileName.endsWith(s)){ // yes, there's only one "=", I do want assignment here
break;
}
}
if(!found){ // after the whole loop it's still false?
ApexPages.addMessage(...);
}

Related

MS Bot Framework: Is there a way to cancel a prompt dialog? [duplicate]

The PromptDialog.Choice in the Bot Framework display the choice list which is working well. However, I would like to have an option to cancel/escape/exit the dialog with giving cancel/escape/exit optioin in the list. Is there anything in PromptDialog.Choice which can be overridden since i have not found any cancel option.
here is my code in c#..
PromptDialog.Choice(
context: context,
resume: ChoiceSelectAsync,
options: getSoftwareList(softwareItem),
prompt: "We have the following software items matching " + softwareItem + ". (1), (2), (3). Which one do you want?:",
retry: "I didn't understand. Please try again.",
promptStyle: PromptStyle.PerLine);
Example:
Bot: We have the following software items matching Photoshop. (1), (2), (3). Which one do you want
Version 1
Version 2
Version 3
What I want if user enter none of above or a command or number, cancel, exit, that bypasses the options above, without triggering the retry error message.
How do we do that?
There are two ways of achieving this:
Add cancel as an option as suggested. While this would definitely work, long term you will find repeating yourself a lot, plus that you will see the cancel option in the list of choices, what may not be desired.
A better approach would be to extend the current PromptChoice to add your exit/cancelation logic. The good news is that there is something already implemented that you could use as is or as the base to achieve your needs. Take a look to the CancelablePromptChoice included in the BotBuilder-Samples repository. Here is how to use it.
Just add the option "cancel" on the list and use a switch-case on the method that gets the user input, then call your main manu, or whatever you want to do on cancel
Current Prompt Choice does not work in that way to allows user select by number. I have override the ScoreMatch function in CancleablePromptChoice as below
public override Tuple<bool, int> ScoreMatch(T option, string input)
{
var trimmed = input.Trim();
var text = option.ToString();
// custom logic to allow users to select by number
int isInt;
if(int.TryParse(input,out isInt) && isInt <= promptOptions.Options.Count())
{
text = promptOptions.Options.ElementAt(isInt - 1).ToString();
trimmed = option.ToString().Equals(text) ? text :trimmed;
}
bool occurs = text.IndexOf(trimmed, StringComparison.CurrentCultureIgnoreCase) >= 0;
bool equals = text == trimmed;
return occurs ? Tuple.Create(equals, trimmed.Length) : null;
}
#Ezequiel Once again thank you!.

Oracle Apex Force Upper Case first Letter.

I Guys
In forms I use,
onKeyUp="this.value = this.value.toUpperCase()"
To force upper-case. However for such as name fields. How do you force the upper letter to be upper-case only while the user is typing. I know INITCAP will do that but need to do as user is typing, if that makes sense.
Any help will be much appreciated.
This is a javascript question then, not and Oracle or APEX question. It shouldn't make any difference what the environment is as long as you have access to the DOM events with javascript functions. e.g. http://www.w3schools.com/jsref/event_onkeyup.asp
If you do a search there are lots of examples to Initcap a string in javascript, just pass in the string and reset the item in the dom e.g.
function capitalizeEachWord(str) {
return str.replace(/\w\S*/g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
I tried to solve this problem.
For that I created JavaScript function which check first letter capital ,if not then it display alert and revert text.
please check following code for text item:
function checkUpper()
{
var x = $x("P6_TEXT");
if (x.value.trim().substring(0,1) != x.value.trim().substring(0,1).toUpperCase()) {
alert ('First letter Must be in upper case');
x.value = x.value.trim().substring(0,x.value.trim().length-1).toString();
}
}
And set item P6_TEXT attribute as
onKeyUp="checkUpper();"
In the field custom attributes put this JS code:
onKeyUp="this.value = this.value.substring(0,1).toUpperCase()+this.value.substring(1).toLowerCase();"
You could use content modifiers from Universal Theme https://apex.oracle.com/pls/apex/apex_pm/r/ut/content-modifiers
I needed text in a page item to be uppercase and under Advanced I set the css classe to
u-textUpper
u-textInitCap - Sets The First Letter In Each Word To Use Uppercase

How do I prevent Grails for doing any further validations if one validation already fails?

I have a Grails command object that I'm using for updating passwords. It looks like this:
class UpdatePasswordCommand {
String password
static constraints = {
password blank: false,
nullable: false,
size: 8..64,
matches: someLongRegex
validator: { String password, command ->
if (someService.isPasswordSameAsUsername(password)) {
return 'password.invalid.sameasuser'
}
}
I left out everything that doesn't pertain to the question I'm asking.
The problem I'm running into is that, whenever this validation triggers, it will trigger ALL the validations, and the command.errors collection will have an error message for each validation failure. This means that, for example, if the user tried to use test for the password, they will get the following error messages:
* Password length must be between 8 and 64 characters.
* Password must not be the same as the user name.
* Password must contain at least one special character, uppercase letter, and digit.
In this case, if the password length is wrong, I want the validation to stop at that point. Likewise, if it's the same as the username, I don't want it to check against the regex. Is there any way I can get the Grails validation to only return the first validation failure for a particular property? Note that it's important that I only want it to stop per property, because if the user doesn't type in his confirm password, for example, I still want to display two error messages:
* Password length must be between 8 and 64 characters.
* You must enter a confirm password.
Shouldn't that be a practice to provide all the validation messages preemptively to the user so that User can rectify or take care of them in one go, instead of rectifying it one by one?
But anyways you can programmatically force to return back only one message at a time something like below:
static constraints = {
password validator: { String password, command ->
def errorMsgs = []
if (!password){
errorMsgs << 'password.invalid.blank' //'password.invalid.null'
return errorMsgs
} else if (!(password.size() in (8..64))){
if (someService.isPasswordSameAsUsername(password)){
errorMsgs << 'password.invalid.sameasuser'
}
errorMsgs << 'password.invalid.length'
return errorMsgs
} else if (/*password not matching YourRegex*/){
errorMsgs << 'password.invalid.specialCharacters'
return errorMsgs
} else if (someService.isPasswordSameAsUsername(password)){
errorMsgs << 'password.invalid.sameasuser'
return errorMsgs
}
}
}
I think we have to take care of the special cases where more than one message is sent back by adding control logic as done above for password length and its match with user name.
Take a look at grails validate, the interesting thing is that you can pass property names to validate(). The second thing is errors property that implements spring Errors interface. You can use it to clean up messages to show only one for property. Write a custom validator as dmahapatro suggested is a good approach.

Magento checkmaxlenght for text attributes

I need to limit text field length for an attribute ("inspiration") similar as for meta_description. I have tried copying the code block in Attributes.php (\app\code\core\Mage\Adminhtml\Block\Catalog\Product\Edit\Tab):
if ($form->getElement('meta_description')) {
$form->getElement('meta_description')->setOnkeyup('checkMaxLength(this, 255);');
}
and replacing "meta_description" with "inspiration", but it doesn't work. Could anyone please help me on this?
Hard to say because you don't define "doesn't work" precisely.
My guess would be, that the <form> containing your inspiration input field is some custom template and doesn't contain the needed JavaScript method checkMaxLength()*.
function checkMaxLength(Object, MaxLen)
{
if (Object.value.length > MaxLen-1) {
Object.value = Object.value.substr(0, MaxLen);
}
return 1;
}
* which is usually only defined in app/design/adminhtml/default/default/template/catalog/product/edit.phtml
Seach for the phtml who build this part of code and make it with jQuery.

Best practice in handling invalid parameter CodeIgniter

Let's say I have a method at Controller named
book($chapter,$page);
where $chapter and $page must be integer. To access the method, the URI will look like
book/chapter/page
For example,
book/1/1
If user try to access the URI without passing all parameter, or wrong parameter, like
book/1/
or
book/abcxyz/1
I can do some if else statements to handle, like
if(!empty($page)){
//process
}else{
//redirect
}
My question is, is there any best practice to handle those invalid parameters passed by user? My ultimate goal is to redirect to the main page whenever there is an invalid parameter? How can I achieve this?
Using the CodeIgniter routing in config/routes.php is pretty useful here, something like this:
$route['book/(:num)/(:num)'] = "book/$1/$2";
$route['book/(:any)'] = "error";
$route['book'] = "error";
Should catch everything. You can have pretty much any regular expressions in the routes, so can validate that the parameters are numeric, start with a lowercase letter, etc..
The best logic here seems to be adding the default values:
book($chapter = 1, $page = 1);
and then checking if they are numeric
So it automatically opens the 1st page of the 1st chapter if there are parameter missing or non-numeric.

Resources