Input validation with pattern Angular 2 - regex

I'm currently writing a simple form in ionic 2 (Angular 2). I was wondering how I'd add a simple regular expression pattern to the validation:
I basically have this:
<form>
<ion-input stacked-label>
<ion-label>{{label.msisdn}}</ion-label>
<input type="text"
[(ngModel)]="msisdn"
ngControl="msisdnForm"
required
maxlength="10"
minlength="10"
pattern="06([0-9]{8})"
#msisdnForm="ngForm"
>
</ion-input>
<button [disabled]="!msisdnForm.valid" block (click)="requestActivationCode()">
{{label.requestActivationCode}}
</button>
</form>
The maxlength, minlength & required are being picked up (the button is disabled if conditions not met). Now I want to limit the input to numeric and prefix it with 06 (Dutch phone number with minimum amount of numbers).
The pattern is however not picked up in the validation. Can I do it this way, or do I need a code approach?

Add the pattern to a variable
var pattern=/06([0-9]{8})/;
and bind the attribute to it
<input type="text"
[(ngModel)]="msisdn"
ngControl="msisdnForm"
required
maxlength="10"
minlength="10"
[pattern]="pattern"
#msisdnForm="ngForm"
>
Seems this PR https://github.com/angular/angular/pull/6623/files needs to land first.
There is still an open issue https://github.com/angular/angular/issues/7595
This prevents pattern being bound to. The pattern needs to be statically added to the DOM (without binding) to work.

I put more details (Angular 2.0.8 - 3 March 2016):
https://github.com/angular/angular/commit/38cb526
Example from repo:
<input [ngControl]="fullName" pattern="[a-zA-Z ]*">
I tested it, and it worked :) - here is my code:
<form (ngSubmit)="onSubmit(room)" #roomForm='ngForm' >
...
<input
id='room-capacity'
type="text"
class="form-control"
[(ngModel)]='room.capacity'
ngControl="capacity"
required
pattern="[0-9]+"
#capacity='ngForm'>
UPDATE September 2017
I just wanna to say that currently when I have more experience, I usally use following 'cheap' approach to data validation:
Validation is ONLY on server side (not in angular at all!) and if something is wrong then server (Restful API) return some error code e.g HTTP 400 and following json object in response body (which in angular I put to err variable ):
this.err = {
"capacity" : "too_small"
"filed_name" : "error_name",
"field2_name" : "other_error_name",
...
}
(if server return validation error in different format then you can usually easily map it to above structure)
In html template i use separate tag (div/span/small etc.)
<input [(ngModel)]='room.capacity' ...>
<small *ngIf="err.capacity" ...>{{ translate(err.capacity) }}</small>
As you see, when there is some error in 'capacity' then tag with error translation (to user language) will be visible. This approach have following advantages:
it is very simple
in angular we not double validation code which is (and must be) in server (in case of regexp validation this can either prevent or complicate ReDoS attacks)
we have full control on way the error will be shown to user (here as egzample in <small> tag)
because in server response we return error_name (instead of direct error message), we can easily change error message (or translate it) by modify only frontend-angular code (or files with translations). So in that case we not need to touch backend/server code.
Of course sometimes (if this is needed - eg. retypePassword field which is never send to server) I make exceptions of above approach and make some validation in angular (but use similar "this.err" mechanism to show errors (so I not use pattern attribute directly in input tag but rather I make regexp validation in some component method after user raise proper event like input-change or save) .

Related

Why is the FORM scope showing fewer values than were actually submitted by this AJAX file uploader?

I'm not sure I understand how to phrase my question, but I believe it's specific to ColdFusion's handling of certain AJAX form data, despite my reference to a specific JavaScript plugin.
I'm trying to implement the FilePond uploader on a ColdFusion 2011 server, and I've got it configured well on the frontend (it uploads the files to tmp folder just fine), but my problem is not knowing how to get ColdFusion to process the extra metadata it sends along with it on every upload. This data doesn't look to me like it comes in the same format as plain old hidden input fields.
When I inspect the network request with Dev Tools, it looks different to me than other forms I've processed. There are two "filepond" entries, one a JSON object and the other the binary image. When I < cfdump var="#form.FilePond#">, I only get the tmp uploaded file path, which I can process. But how do I access the JSON in my screenshot containing the "parentid"? Nothing I've tried, like form.FilePond[1], seems to work and throws errors.
Update with output from CF form processing page:
1st line is output of Form.FilePond.
2nd is cfdump of Form.
3rd is cfdump URL.
4th is cfdump of getHttpRequestData()
Update:
Bugs filed for CF2016 (core support ending for CF11 after April 2019)
CF-4204103 -
FORM scope is missing values when same named fields include type=file
CF-4204102 - sameFormFieldAsArray setting doesn't work with enctype="multipart/form-data"
After some testing, I've concluded it's a ColdFusion bug.
Issue:
The issue seems to occur under these conditions
Request is a multipart/form-data POST
Contains multiple fields with the same name
At least 1 of those fields is a file field i.e. type="file"
The first field submitted (within the group) is NOT a file field
Under those conditions, ColdFusion seems to ignore everything before the first file field. (If you check the filepond source ut confirms the metadata field is submitted before any file fields). That's why the metadata value doesn't appear when dumping the FORM scope.
Note, the this.sameFormFieldsAsArray setting has no effect because it doesn't work with multipart/form-data requests.
Test Case
Below is a test case. Notice the results are what you'd expect when the same named field occurs after the first file field?
<cfdump var="#form#" label="Form scope">
<form method="post" enctype="multipart/form-data">
<br>First:
<input type="file" name="fileFirst"><br>
<input type="text" name="fileFirst" value="Lions"><br>
<br>Last:
<input type="text" name="fileLast" value="Tigers"><br>
<input type="file" name="fileLast"><br>
<br>Middle:
<input type="text" name="fileMiddle" value="Bears"><br>
<input type="file" name="fileMiddle"><br>
<input type="text" name="fileMiddle" value="Oh My"><br>
<input type="submit">
</form>
Workaround
This blog provides a workaround using an undocumented feature of the FORM scope. Using form.getPartsArray() provides access to both "filePond" fields allowing you to extract the value of the dropped field. Not ideal, but does work until the issue is fixed.
Keep in mind this is an undocumented feature, so be sure to isolate the code for easier alterations in case Adobe alters or removes that function in the future (which they've done before, so fair warning!).
<cfscript>
// dump raw form fields
for (part in form.getPartsArray()) {
writeDump({ fieldName = part.getName()
, isFile = part.isFile()
, fieldValue = (part.isFile() ? part.getFileName() : part.getStringValue())
}
);
}
</cfscript>

HTML5 number input field step attribute broken in Internet Explorer 10 and Internet Explorer 11

It appears some of my website's users are experiencing issues when attempting to insert values into input fields of type number with the step attribute set.
I am using Django 1.6 to render the forms to HTML.
The number fields map to an underlying DecimalField model field with max_digits=25 and decimal_places=5
This results in the following example html being rendered for the number field:
<input type="number" value="" step="0.00001" name="quantity" id="id_quantity">
The step attribute I know is not yet supported in FireFox but is in Opera, Chrome, Safari and IE10+
Everything works fine in all browsers except IE10 and IE11. In the above example the maximum range that can be entered is -227 to 227 in IE10 and IE11. If I try to enter a lower or greater value (respectively) than this I get a 'You must enter a valid value' error and cannot submit the form.
According to http://www.w3schools.com/tags/att_input_step.asp
The step attribute specifies the legal number intervals for an element.
Example: if step="3", legal numbers could be -3, 0, 3, 6, etc.
So in my user's example they were attempting to enter 20000 as the value which failed in IE10 and IE11. If my calculations are correct 20000 falls correctly into an interval of 0.00001
A solution for me could be to remove the step attribute from all my forms that use a number field, either via the django forms or using javascript, but I think this would be a very messy solution and one that goes against the grain of HTML5.
Has anyone else encountered a similar problem, have I done something wrong or is this a bug in IE10 and IE11?
Any thoughts, comments or answers welcome. In the meantime I will be forced into providing my usual solution to affected users by suggesting they use a browser that works.
You're not alone, IE is pretty buggy on this.
I'm not sure about IE10, I can only test IE11 right now, and it kinda treats number fields as date fields, which it actually shouldn't support at all, still when passing for example 20000 it says "Insert a valid date" (originally "Geben Sie ein gültiges Datum ein").
And indeed, when entering something like 01.01.2000 or 01-01-2000 it passes validation, though even 20000.01.123456789 passes, just like 90000 or 0.foobar, so I guess the validation is just totally messed up.
So for the time being you'll probably have to use some kind of polyfill in case you want to please IE users.
IE10's HTML5 form validation is really buggy in this case, so you might want to consider disabling HTML5 form validation for this form.
You can do this by adding a novalidate attribute to the form tag. For example, you might want to do something like this:
<form method='POST' action='.' novalidate='novalidate'>
<input type="number" value="" step="0.00001" name="quantity" id="id_quantity">
</form>
Setting novalidate will tell the browser to not try to be useful, which should work out your issue. However, please be aware that this will disable the HTML5 validation for the whole form for all browsers. If you need to keep this for some browsers while removing it from IE, you'll have to add the novalidate attribute via Javascript on page load after checking the browser user agent. This user agent can be spoofed however so it's not an ideal solution.
I ran into the same issue and adding step="any" at the field level fixed the issue for me.
It looks like IE10+ need a MIN and MAX value in order to work properly. If you defines these values it will work just fine with the 10000 value:
<input type="number" value="" step="0.00001" min="-100000" max="100000" name="quantity" id="id_quantity" />
Seems that step attributes for numer input just implemented as for Range Input which needs min, max and step values.
If really you are not able to define a min and max value, you must use Javascript to do that.

Django: How can I invisibly pass a variable to another template?

I have three templates in my project—we'll call them first.html, second.html, third.html.
first.html gets a string from the user, using an <input> tag:
<input type="radio" name="selection" value="example_string" />
second.html displays this string using {{selection}}. (In my views.py, I got the value using request.POST.get and render_to_response().)
The question is: how do I send this value from second.html to third.html? One of my attempts—using a <span> tag to save the information in a variable—is illustrated below, but it doesn't seem to work.
<span name="selection" value={{selection}}>{{selection}}</span>
Edit: The following line works by creating a dummy single radio button. I don't know why it shouldn't be possible to create a variable without an <input> tag [visible to the user].
<input type="radio" name="selected" value={{selected}} checked="checked" />
You need to understand how the web works: each page is entirely separate, and is requested using a separate request.
Your basic options are: save data on the client side, or post it back to the server.
Both options can be performed with javascript, or posting back can also be performed by posting the form back to the server.
If you want to send it back to the server, it will have to be stored in the current session, or in a model.
There are many javascript libraries. If you want to use them, I suggest you google around the subject.
Answering my own question, now that I've found the answer on Django's documentation.
There's a special kind of <input> tag precisely for this: "hidden". The following line accomplishes the same as was asked in the question, but without a dummy element visible to the user:
<input type="hidden" name="selected" value={{selected}} />

issues with ngPattern directive

I've this code:
<form name="test">
<input type="text" ng-model="code" name="code" ng-pattern="/^code_[0-9]+$/"/>
<div ng-show="test.code.$dirty && test.code.$invalid">
Error:
<span ng-show="test.code.$error.pattern">Pattern fail.</span>
</div>
</form>
I have 2 issues with this code:
Strings like " code_232 ", "code_232 " " code_232" pass the validation. I'm not expert with regex, so this could be an issue simply related to the regex i wrote: /^code_[0-9]+$/
If i start writing "code_23892" (a correct string), i get the error
message while i'm still writing (test.code.$error.pattern = true). Is there a built-in way to avoid this? So my desidered behaviour is:
If i write "cod", and the input has still focus: no error
If i write "cod" and the input loses focus: error.
If i write "a", "ca", "coa" etc.: error, cause the pattern is already violated.
Is this already possible, or i've write a custome validation directive to achieve this?
Thanks in advance.
The reason that whitespace doesn't trigger a failed validation is because ng-model automatically trims the value. If you don't want that, you can add ng-trim="false" to your <input />. Note that ng-trim is a quite new attribute, so you might have to update your Angular version.
About your second question; I don't think you can avoid the validation to run during the time you type, but you could change your code to only display the error when the input looses focus. I don't think that something like ng-blur and ng-focus exists, but it should be pretty simple to implement them.

Cross Site Scripting with Hidden Inputs

My company gave me the task of resolving all security issues with a particular application. The security tream reported a cross site scripting error. The error lies in the following input field:
<input type="hidden" name="eventId" value="${param.eventId}"/>
The report from security wasn't very detailed, but the say they can make a POST request to the page that has the above tag including the following malicious code:
eventId=%22%3e%3csCrIpT%3ealert(83676)%3c%2fsCrIpT%3e
And that when the page reloads, it will have the following:
<input type="hidden" name="eventId" value=""><sCrIpt>alert(83676)</sCrIpt></value>
I am trying to "be the hacker" and show the vulnerability. But I can't figure out how they manage to get that script in there. I am guessing they include it as a URL parameter in the GET request for the form, but when I try to do it myself I get a 403 error. Does anyone know how the vulnerability can be shown?
I know there is a number of XSS questions on the site, but none seem to hit this topic.
So, I am not sure why, but my original hunch was correct. The script can be put on as a URL parameter. For some reason though, this was not working with our staging site. Only with running the application locally. I am not sure why, but this works (only locally):
http://localhost:8080/myUrl/MyAction.do?eventId=%22%3e%3csCrIpT%3ealert(83676)%3c%2fsCrIpT%3e
Doing that, you see an alert box pop up. I am planning to fix it using JSTL functions.
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
...
<input type="hidden" name="eventId" value="${fn:escapeXml(param.eventId)}"/>
Install [TamperData][1] add-on in firefox browser which let you edit the data before submitting. Doesn't matter if it's in POST or GET.
By using this hidden fields can be edited.
What you want to do to fix the problem, is to HTMLAttributeEncode the value before putting it inside the value-attribute. See OWASP ESAPI or MS AntiXSS for methods for doing HTML attribute encoding.
Seeing how the attack string is URL encoding, I think you guess about including it as a GET parameter seems reasonable.
I used the OWASP ESAPI API as the legacy jsp's didn't have JSTL available. This is what I used:
<input type="hidden" name="dataValue" value="<%=ESAPI.encoder().encodeForHTMLAttribute(dataValue)%>">
You can also use the API to filter request.Parameter() which I also needed, as in:
String userURL = request.getParameter( "userURL" )
boolean isValidURL = ESAPI.validator().isValidInput("URLContext", userURL, "URL", 255, false);
if (isValidURL) {
link
}
and:
String name = (String) request.getParameter("name");
name = ESAPI.validator().getValidInput("name ", name , "SafeString", 35, true);