When validating a form, should I assume a field is valid or invalid? - forms

When I write validation code for a web form, I usually assume that the content of a field is valid and attempt to prove that it is invalid. Is it a better practice to assume that the content of the field is invalid and then attempt to prove that it is valid?
A very simple example (pseudo code):
function isValid( formFieldValue, minLength, maxLength ) {
valid = true;
fieldLength = length( formFieldValue );
if( fieldLength < minLength ) {
valid = false;
}
if( fieldLength > maxLength ) {
valid = false;
}
return valid;
}
Would it be better to assume that the field in question is invalid and modify my checks accordingly?
Please note - I'm not talking about XSS protection or input filtering. We can never assume that user input is safe. I am talking about validating things like minimum/maximum length or a valid e-mail address in a form field.

I think when you just talk about things like length etc. it makes no big difference. But I would ever assume that the input is invalid and prove that it's not, because I do the same with probably XSS input.

I think that better idea is to assume wrong input and to prove validity. It's easier.
For javascript allready exists number of libraries that solves your problem.
e.g.
Backbone.Forms https://github.com/powmedia/backbone-forms
jQuery validatin plugin http://bassistance.de/jquery-plugins/jquery-plugin-validation/

The point is whether your all conditions run or not.
Case1: Assume that a form is valid and then check for its invalidity by checking for example 2 conditions.
Case2. Assume that a form in invalid and then check 2 conditions whether it is invalid?
In both cases you will have to check for all conditions to satisfy because you want to validate all your fields. So whether you assume it is valid or invalid at start doesn't matter we mostly check for invalidity.

Related

What is the correct way to express "select all when nothing is specified in parameter"?

Let's say we have an HTTP endpoint to get all elements by name?
GET /elements?name={name}
{name} can have a value of CSV or be absent
valid:
GET /elements?name=Bill,Mary,Ann
GET /elements?name=Mike
GET /elements
invalid:
GET /elements?name=
Somehow we find out in controller that name is not passed. We know that the contract implies to return all values for elements. Possible decisions on further actions (I've seen in different projects) are:
using a NULL or a "dummy" substitution like a secret char sequence "!#$#%#$" and juggling them in database while building a query
using if (present) { executeQueryA } else { executeQueryB } logic
I am not sure I like either of these approaches, because when there is more than one optional filter these designs become unmaintainable. Something makes me believe that there is a better way to handle the situation.
What would be a proper design on back-end and in database query to handle the case "select all" when nothing is given? Just a general idea and some pseudo-code will be much appreciated.

ADFS PowerShell Claims Rule Combination Sytax

After some success with simple rules, having trouble in ADFS Claim Rules PowerShell SnapIn with:
How to delete rules. EDIT: => poor man's way appears to be just define a new empty rule set.
How to append rules without setting them all in one command.
Syntax for logical decisions within a rule. My attempt:
Set-AdfsAdditionalAuthenticationRule -AdditionalAuthenticationRules 'c1:[type ==
"http://schemas.microsoft.com/ws/2012/01/insidecorporatenetwork", value == "false"] &&
(NOT EXISTS([type == "http://schemas.microsoft.com/2012/01/requestcontext/claims/x-ms-client-ip",
Value =~ "^(?i)2003:6a:7d12:3f58:148:f23:cdc4:4181$"]))
=> issue(type =
"http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", value =
"http://schemas.microsoft.com/claims/multipleauthn" );'
Produces an error at the "NOT EXISTS" no matter what I do. Any help greatly appreciated. The idea is to require all external IPs except the one in the list of IPs (regex) to use MFA.
EDIT: I TRIED THE FOLLOWING
the only thing that I still can't get working is the IP-address check. Is there a way I can debug to see what is happening (ip found or result of regex etc.)?
$RhtMfaClaimRule = 'NOT EXISTS([type ==
"http://schemas.microsoft.com/2012/01/requestcontext/claims/x-ms-client-ip", Value =~ "^(?i)81.151.139.145$"]) => add(type = "http://schemas.company.com/temp", value = "true" );
c1:[type == "http://schemas.company.com/temp"] &&
c2:[type == "http://schemas.microsoft.com/ws/2012/01/insidecorporatenetwork", value == "false"] => issue(type = "http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", value = "http://schemas.microsoft.com/claims/multipleauthn" );'
Set-AdfsAdditionalAuthenticationRule $RhtMfaClaimRule
EDIT: Learned from logging
The rules appear to be ok since a regexp of ".asterix" for the filtered IP turns off MFA from external as expected. But as soon as I change it to anything but .asterix, I get prompted for the MFA again. So, suspecting the client-ip claim, looking at the logs. I see the calling IP is visible in the request context header, so far so good, but in the thousands of trace entries, I do not see the client-ip claim yet. I suspect I have to tell Office365 to forward this somewhere in my ADFS-daschboard "Edit Claim rules for Microsoft Identity Platform". Any idea what I need to precisely add there for this client-ip claim to be forwarded?
EDIT. Probably SOLVED
The posts shown below helped. The ms-client-ip claim used above is apparently only for inhouse clients. Desperation led me to really look at the claim details, and replacing the x-ms-client claim with the following one from the request context apparently does the trick -- initial tests successful.
http://schemas.microsoft.com/2012/01/requestcontext/claims/x-ms-forwarded-client-ip
You can't AND EXISTS rules AFAIK.
Try something like:
NOT EXISTS([type == "http://schemas.microsoft.com/2012/01/requestcontext/claims/x-ms-client-ip",
Value =~ "^(?i)2003:6a:7d12:3f58:148:f23:cdc4:4181$"]))
=> add(type =
"http://schemas.company.com/temp", value = "true" );
and then:
c1:[type == "http://schemas.company.com/temp"] &&
c2:[type ==
"http://schemas.microsoft.com/ws/2012/01/insidecorporatenetwork", value == "false"]
=> issue(type =
"http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", value =
"http://schemas.microsoft.com/claims/multipleauthn" );'

Get statuscode text in C#

I'm using a plugin and want to perform an action based on the records statuscode value. I've seen online that you can use entity.FormattedValues["statuscode"] to get values from option sets but when try it I get an error saying "The given key was not present in the dictionary".
I know this can happen when the plugin cant find the change for the field you're looking for, but i've already checked that this does exist using entity.Contains("statuscode") and it passes by that fine but still hits this error.
Can anyone help me figure out why its failing?
Thanks
I've not seen the entity.FormattedValues before.
I usually use the entity.Attributes, e.g. entity.Attributes["statuscode"].
MSDN
Edit
Crm wraps many of the values in objects which hold additional information, in this case statuscode uses the OptionSetValue, so to get the value you need to:
((OptionSetValue)entity.Attributes["statuscode"]).Value
This will return a number, as this is the underlying value in Crm.
If you open up the customisation options in Crm, you will usually (some system fields are locked down) be able to see the label and value for each option.
If you need the label, you could either do some hardcoding based on the information in Crm.
Or you could retrieve it from the metadata services as described here.
To avoid your error, you need to check the collection you wish to use (rather than the Attributes collection):
if (entity.FormattedValues.Contains("statuscode")){
var myStatusCode = entity.FormattedValues["statuscode"];
}
However although the SDK fails to confirm this, I suspect that FormattedValues are only ever present for numeric or currency attributes. (Part-speculation on my part though).
entity.FormattedValues work only for string display value.
For example you have an optionset with display names as 1, 2, 3,
The above statement do not recognize these values because those are integers. If You have seen the exact defintion of formatted values in the below link
http://msdn.microsoft.com/en-in/library/microsoft.xrm.sdk.formattedvaluecollection.aspx
you will find this statement is valid for only string display values. If you try to use this statement with Integer values it will throw key not found in dictionary exception.
So try to avoid this statement for retrieving integer display name optionset in your code.
Try this
string Title = (bool)entity.Attributes.Contains("title") ? entity.FormattedValues["title"].ToString() : "";
When you are talking about Option set, you have value and label. What this will give you is the label. '?' will make sure that the null value is never passed.

Zend framework - how to allow empty field for form element

I'm using this construction for my element:
$freetext = $this->CreateElement('textarea', 'freetext')
->setLabel('Comments')
->setAttrib('class','input-textarea')
->setOptions(array('rows' => '2', 'cols'=>'30'))
->addValidator('StringLength', false, array(0,500))
->addFilter('HtmlEntities')
->addFilter('StripTags')
->setRequired(true);
I want to add an "allowEmpty" to this but can't find the correct syntax. I was hoping for something like:
... ->addValidator('allowEmpty', false, true)
But this does not work.
Edit: I've changed the setRequired() to true - I want to allow empty string as an acceptable value on a require field.
Regardless of usage, how do I add this option to my element?
->setRequired(false);
this is enough if you want to allow an empty string and save an empty string to database.
if you want the field to be optional and keep null value in database if nothing is given, add:
->addFilter(new Zend_Filter_Null)
$freetext = $this->CreateElement('textarea', 'freetext')
->addValidator('StringLength', false, array(10,500))
->setRequired(false);
Your code should already do that, the setRequired(false) method do what you're asking for, i.e. if the value is not submitted then validators won't be run.
Do you have any issue with the code you've written, some validation error messages or something else?
Update
I've changed the setRequired() to true - I want to allow empty string as an acceptable value on a require field.
What is the semantic in setRequired(true) and allowing the empty string as a valid value? Or better what do you require if the element can be empty?
What you've asked in the edit is a no sense, because if an element is required it MUST have a value different from the empty string. If you need to accept the empty string as a valid value just use setRequired(false). When you get form values with Zend_Form::getValues() or Zend_Form_Element::getValue() you'll obtain the empty string as result.
Anyway here it's the explanation of setRequired and setAllowEmpty from ZF manual:
Using the defaults, validating an Element without passing a value, or
passing an empty string for it, skips all validators and validates to
TRUE.
setAllowEmpty(false) leaving the two other mentioned flags
untouched, will validate against the validator chain you defined for
this Element, regardless of the value passed to isValid().
setRequired(true) leaving the two other mentioned flags untouched,
will add a 'NotEmpty' validator on top of the validator chain (if none
was already set)), with the $breakChainOnFailure flag set. This
behavior lends required flag semantic meaning: if no value is passed,
we immediately invalidate the submission and notify the user, and
prevent other validators from running on what we already know is
invalid data.
If you do not want this behavior, you can turn it off by passing a
FALSE value to setAutoInsertNotEmptyValidator($flag); this will
prevent isValid() from placing the 'NotEmpty' validator in the
validator chain.

Codeigniter: Submitting Forms

How do I submit a form that can do two different things based on the URI?
For example, if the URI contains a string "new" the form will submit differently than it would if "new" were not in the URI.
I'm having trouble implementing this, as when a form is submitted, it takes the URI of whatever "form_open" says.
Altering the form_open path is probably not the way to do this. How are you using this? Does the person filling out the form affect the "new" string?
What I would do is put a hidden input on the form and set THAT value to "new". Then in the controller, use a GET to take the value of the input form, and do a simple IF / ELSE statement based off the value of that variable.
This way, you could setup several different ways to use the same form - hidden=new, hidden=old, hidden=brandnew, hiddend=reallyold could all process the form values differently, even sending them to different tables in your DB or whatever.
Kevin - I thought I'd done something like this before and I had - here's a quick look:
In routes.php:
$route['some/pathname/(:any)'] = "my_controller/my_function/$1";
Then in mycontroller.php:
function my_function($type)
{
if ($type == "new") {
do this }
elseif ($type == "update)" {
do this }
}