Regex expression with Validators.pattern for just integer number - regex

I am trying to create a validator for only integers (e.g., 60) using Regex.
Here how I am trying to do it:
meter: ["", Validators.required, Validators.pattern(/[0-9]/)]
It does not work, but I have to say I am not familiar with this technique.
Anyone could shed some light on how I could modify this expression to accept just integers?
This number is for height, and the height is devided into meters and centimeter.
I have searched, but I could find for decimals and so, somehow, maybe because it is too trivial, for just integers, I cannot find, in fact, I have found yesterday here, but I cannot find the answer anymore I have found, I was looking for another thing.

First of all, you don't need a custom validator to do this, as regular expression validation is already a built-in validator.
Secondly, the way you apply validators to your form controls depending on either you are using template-driven forms or reactive forms.
If you are using template-driven forms (which is commonly used for Angular beginners), simply make your input control template look like this:
<input type="number" name="meter" required pattern="[0-9]" [(ngModel)]="meter">
If you are using reactive forms, just assign both "required" and "pattern" validator to your form control.
<input type="number" [formControl]="myControl">
myControl = new FormControl(null, [
Validators.required,
Validators.pattern("[0-9]+")
]);
When using it in a reactive form control, you can pass in either a string or a regex object, there are differences between them as stated in official docs:
If a string is passed, the ^ character is prepended and the $ character is appended to the provided string (if not already present), and the resulting regular expression is used to test the values.
Lastly, a Stackblitz example attached to show simple usage of this validator in both template/reactive forms.
https://stackblitz.com/edit/angular-ivy-neux3n

Related

Django: display a preview of an object's attribute - Class based views

Using a ListView Class-based-view, I am looping over the objects present in the database of a certain model in my HTML template, and, for instance, I can access an object's "body_text" attribute with the following syntax: {{object.body_text}}
What if I wanted to only show the first 20 characters of that "body_text" attribute in my HTML template?
How can I set that?
1st Method
Use the truncatechars filter in your HTML template.Truncates a string if it is longer than the specified number of characters. Truncated strings will end with a translatable ellipsis character (“…”).
{{object.body_text|truncatechars:20}}
Reference:
https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#truncatechars
2nd Method
Use the slice filter in your HTML template.
{{object.body_text|slice:":20"}}
Referernce: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#slice
Found it, eventually.
Use the |slice:":" filter in your HTML template.
For example, if you only want to display the first 10 characters of a given attribute, use:
{{object.body_text|slice:":10"}}

Multiple Regex Validation against a value

I want to validate a text box input with below requirement
Text must be integer
Value of text must be between a predefined Max Value and predefined Min Value
** I don't want to use RangeAttribute.I want to use regular expression which I want to store in database and will get applicable when View will get rendered.
How we can do this in c# using multiple regex?
IF you want to restrict it in HTML, so you are sure the value you will receive is already a number you can do it like this:
Quantity (between 1 and 5): <input type="number" name="quantity" min="1" max="5">
IF this is an MVC project, you should restrict this in your ViewModel by setting your property to be an Integer (int), use annotations to enforce things like
[Required]
or
[Range(10, 1000, ErrorMessage = "Value for {0} must be between {1} and {2}.")]
Depending on what your project is built in (Webpages or MVC) this can be done differently.

Best way to go about sanitizing user input in rails

I've read a lot about this and know there are many related questions on here, but I couldn't find a definitive guide for how to go about sanitizing everything. One option is to sanitize on insert, for example I have the following in my model
before_validation :sanitize_content, :on => :create
def sanitize_content
self.content = ActionController::Base.helpers.sanitize(self.content)
end
Do I need to run this on every field in every model? I'm guessing the :on => :create should be removed too so it runs when updates too?
The other option is to sanitize when data is displayed in views, using simple_format, or .html_safe or sanitize(fieldname). SHould I be sanitizing in all my views for every single field, as well as on insert? Having to do this manually everywhere doesn't seem very railsy
Thanks for any help
TL;DR
Regarding user input and queries: Make sure to always use the active record query methods (such as .where), and avoid passing parameters using string interpolation; pass them as hash parameter values, or as parameterized statements.
Regarding rendering potentially unsafe user-generated html / javascript content: As of Rails 3, html/javascript text is automatically properly escaped so that it appears as plain text on the page, rather than interpreted as html/javascript, so you don't need to explicitly sanitize (or use <%= h(potentially_unsafe_user_generated_content)%>
If I understand you correctly, you don't need to worry about sanitizing data in this manner, as long as you use the active record query methods correctly. For example:
Lets say our parameter map looks like this, as a result of a malicious user inputting the following string into the user_name field:
:user_name => "(select user_name from users limit 1)"
The bad way (don't do this):
Users.where("user_name = #{params[:id}") # string interpolation is bad here
The resulting query would look like:
SELECT `users`.* FROM `users` WHERE (user_name = (select user_name from users limit 1))
Direct string interpolation in this manner will place the literal contents of the parameter value with key :user_name into the query without sanitization. As you probably know, the malicious user's input is treated as plain 'ol SQL, and the danger is pretty clear.
The good way (Do this):
Users.where(id: params[:id]) # hash parameters
OR
Users.where("id = ?", params[:id]) # parameterized statement
The resulting query would look like:
SELECT `users`.* FROM `users` WHERE user_name = '(select user_name from users limit 1)'
So as you can see, Rails in fact sanitizes it for you, so long as you pass the parameter in as a hash, or method parameter (depending on which query method you're using).
The case for sanitization of data on creating new model records doesn't really apply, as the new or create methods are expecting a hash of values. Even if you attempt to inject unsafe SQL code into the hash, the values of the hash are treated as plain strings, for example:
User.create(:user_name=>"bobby tables); drop table users;")
Results in the query:
INSERT INTO `users` (`user_name`) VALUES ('bobby tables); drop table users;')
So, same situation as above.
Let me know if I've missed or misunderstood anything.
Edit
Regarding escaping html and javascript, the short version is that ERB "escapes" your string content for you so that it is treated as plain text. You can have it treated like html if you really want, by doing your_string_content.html_safe.
However, simply doing something like <%= your_string_content %> is perfectly safe. The content is treated as a string on the page. In fact, if you examine the DOM using Chrome Developer Tools or Firebug, you should in fact see quotes around that string.
Because I always appreciate when I find the source of knowledge and code on any SO answer, I will provide that for this question.
Both ActiveRecord and ActionController provide methods to sanitize sql input.
Specifically from ActiveRecord::Sanitization::ClassMethods you have sanitize_sql_for_conditions and its two other aliases:
sanitize_conditions and sanitize_sql. The three do literally the exact same thing.
sanitize_sql_for_conditions
Accepts an array, hash, or string of SQL conditions and sanitizes
them into a valid SQL fragment for a WHERE clause.
However, in ActiveRecord you also have
sanitize_sql_for_assignment which
Accepts an array, hash, or string of SQL conditions and sanitizes them
into a valid SQL fragment for a SET clause.
Note that these methods are included in ActiveRecord::Base and therefore are included by default in any ActiveRecord model.
On the other hand, in ActionController you have ActionController::Parameters which allows you to
choose which attributes should be whitelisted for mass updating and
thus prevent accidentally exposing that which shouldn't be exposed.
Provides two methods for this purpose: require and permit.
params = ActionController::Parameters.new(user: { name: 'Bryan', age: 21 })
req = params.require(:user) # will throw exception if user not present
opt = params.permit(:name) # name parameter is optional, returns nil if not present
user = params.require(:user).permit(:name, :age) # user hash is required while `name` and `age` keys are optional
The parameters magic is called Strong Parameters, docs here.
I hope that helps anyone, if only to learn and demystify Rails! :)

Custom field / form field (maybe widget?) for storing values for a string format

I wish to create a model where I can store a string formatting pattern as well as accompanying values.
Example:
Pattern = 'Strength deals %d more damage for each %f%% critical chance'
Values = [2, 1.50]
The pattern only has to store ints and floats. My initial thought was to simply create a custom field, validate the values and that would be it. You can see my field here
However, this simply lets me save the list. I still need some way to figure out how many values to validate, check that it matches the other field (a simple CharField). This could be done "manually", but I would like to create a custom form field that would generate X input boxes that match the number of wildcards in the pattern.
Question 1: Is there any way to "link" two fields so that one can act on the value of the other?
Question 2: To create this, I would probably need to create a new form widget, but is this possible? Any hints as to how to start?
This may not exact answer, but writing it in comment is not feasible.
Another option would to store as JSON string in the model. Like
[{ "Pattern": 'Strength deals %d more damage for each %f%% critical chance',
"Values" : [2, 1.50]
}]
Use custom form field to input/output as JSON input. There are quite a few implementation available when searched on google.
With this approach, you can try to validate the inputs, so that format string and number of variables provided matches.

Ordered list form value in Django form

Is there a way to submit an unbounded list of values as part of a form and retrieve it in Django as an ordered list? I saw this question: Django equivalent of PHP's form value array/associative array which makes sense, however since the values are submitted with the same name as separate POST values I assume they are unordered.
Ideally, I'd like this on the front end:
<input type="hidden" name="list[0]" value="blah">
<input type="hidden" name="list[1]" value="blah2">
<input type="hidden" name="list[2]" value="blah3">
and be able to see which list item occurred in which position when the form was submitted.
I want it sorted in an order determined in the front-end HTML, not sorted by value. I know about getlist(), but that doesn't preserve order.
As far as I'm aware, the square bracket notation is a convention of PHP rather than HTML per se.
There seems to be a Django workaround using dot notation to generate expanded dictionaries (http://stackoverflow.com/questions/2527476/phps-form-bracket-trick-is-to-djangos). I haven't tried it, but it seems it could work
The other solution is to parse the form names yourself, extracting the number from the square brackets and generating your own ordered list
(DISCLAIMER: I'm a mere casual programmer, and am more than willing to acknowledge that im wrong - but hopefully the SO moderation system will moderate any silly comments into oblivion)