prevent negative numbers but accept decimals? HTML [duplicate] - html

This question already has answers here:
Is there a float input type in HTML5?
(14 answers)
Closed 4 years ago.
Is there's a way to prevent negative numbers but accept decimals? I'm using PHP and HTML
<input type="number" min="0" id="Student" name="course[]" value="<?php echo $_POST['course'][3]; ?>"/></p>

Your code theoretically works. It prevents negative numbers and accepts decimals.
I think what you're really asking is this: Is there a float input type in HTML5?
to which the top answer suggests that you would write:
<input type="number" min="0" step="0.01" name="course[]">
The thing that matters the most though is not client-side validation, but server-side validation. In the PHP code that accepts this input, you have to validate that the input is valid as follows:
if(is_numeric($_POST['course'][3]) && floatval($_POST['course'][3]) >= 0) {
// The rest of your code.
}
To do this for all the courses, you would most likely write:
foreach($_POST['course'] as $k => $v) {
if(!(is_numeric($v) && floatval($v) >= 0)) {
echo "Input needs to be a number.";
break;
}
// Process the course $_POST['course'][$k] here.
}
The main reason you have to check if it's a number in server-side too is that someone with certain knowledge about browsers can just open the browser console and edit the attributes of the input removing the type="number", allowing him to send you virtually any text.
Someone with even more knowledge can send you cURL requests.

Related

Limit characters in input box to non-numbers only with Angular

I see that a lot of people are using directives to solve this problem which I find annoying. While I like directives it feels like massive overkill.
I have an input
<input maxlength="4" type="text" id="CustomerNameKey" name="CustomerNameKey" class="form-control" ng-model="detail.customerNameKey" placeholder="Customer Name Key" required />
I thought the business requirement was just limit to 4 alphanumeric , so this code works great
maxlength="4"
However I cannot allow any number ( so only allowing a-z / A-Z )
Seems like I see
angular documentation with it throwing out warning to the page, but it is not restricting the input I prefer to not allow more than 4 characters to be typed , and only alpha
all these directive solutions seem crazy to me
Any inline regex i can do?
As mentioned in the comments, the best approach is to use a directive. In fact, I just made one, you can see it in the jsFiddle
myApp.directive('smartInput', [
function() {
return {
restrict: 'E',
scope: {
value: '='
},
link: function(scope, element) {
element.bind('keypress', function(event) {
if (event.key.search(/\d/g) != -1) {
event.preventDefault();
}
});
},
template: '<input type="text" ng-model="value">'
}
}
]);
http://jsfiddle.net/HB7LU/28432/
EDIT:
HTML5 supports input checking in html input elements by use of the pattern attribute, although it does not respond in real time and must be used with a submit. If this is the functionality you are looking for, you can get away with a simple element:
<input type="text" name="charInput" pattern="[A-Za-z]" title="Not Numbers">
more information can be found on the w3 page on the pattern attribute. Also noteworthy is the fact that this does not appear to be supported by safari

Min being ignored in <input> tag

Ok so I don't know the first thing about knockout.js and that may be my issue.
I am maintaining an ASP.NET application and I was tasked with changing an html
file in the solution that uses knockout.js. Here is the line of code that is having an issue:
<input type="number" class="form-control" data-bind="value: Quantity, uniqueId: Quantity, uniqueMod: 'measure-quantity', enable: IsNotListMeasureIndividually() && !IsNotInstalled()" />
This input tag is allowing the user to enter a negative number and we dont want to allow that. So what I tried was to add min="1" to the tag. The result was it got ignored then moved on to the next set of lines of code
then blew up.
Is the reason that the min is not working because this is not just a simple input tag and includes knockout references in the data-bind?
If so, how can I go about putting in the desired validation to
only accept positive numbers? Please help and remember I know nothing about knockout. Thank you!!
Try Something like this. Use javascript to ignore the keypress of the negative symbol. I don't think that all browsers support the number type Of course you will need the correct handle to assign the keydown event to the right input box.
document.getElementByTagName('input')[0].addEventListener('keydown',function(e){
if ( event.which == 109 || event.which == 173 ) {
event.preventDefault();
}
});
jsfiddle
This combined with the min="0" attribute will prevent the number block from allowing negative numbers.

Force leading zero in number input

I'm writing an alarm web app. I have two number inputs, one for the hours, one for the minutes. Thus, when I use my keyboard arrows, they go from 0 to 23/59. Is there an HTML native way to make them go from 00 (01,02, et.) to 23/59 instead ?
I'm only worried about the UI aspects as my JS manages the missing 0 anyway.
EDIT - As requested :
What I have :
What I want :
Instead of going from 0,1,2 to 59, I'd like to automatically have a leading 0 when the number is smaller than 10 (00,01,02 to 59).
I use this to just prepend zeros as needed:
<script>
function leadingZeros(input) {
if(!isNaN(input.value) && input.value.length === 1) {
input.value = '0' + input.value;
}
}
</script>
And I just call that on the input's various events how ever works best for me, for instance:
<input type="number"
value="00"
onchange="leadingZeros(this)"
onkeyup="leadingZeros(this)"
onclick="leadingZeros(this)" />
It's not an ideal solution, mainly because there's a slight visual change as the user changes the number and the zero is prepended, but it works for me :)
Edit: Forgot to mention, I appreciate the answer asked for a native solution without javascript, but I wanted to provide something for people landing here through a Google search.
I'm afraid there is not native HTML way to do that unless using a Select tag. If you are using a text input you have to add the leading 0 on the 10 first values by javascript.
The correct, modern solution to OP's problem would be to use a input with type=time and then they don't have to worry about leading zeros or any of this other stuffs.
Adding on to some of the other answers that suggest using an event listener. I've tested this with jquery in chrome and it seems to work well with the padding without the slight flashing side effect.
<input type="number" id="input-element-id" value="00">
<script>
$('#input-element-id').on('input', function() {
const value = $(this).prop('value')
$(this).prop('value', value.padStart(2, '0'))
})
</script>

Issue with hidden input and very large values in HTML and ASP.NET MVC 3 Razor

Since there appears to be a 1024 character limit for hidden input values, what does everyone do for values in excess of this limit? Can a hidden file input (<input type="file" value="some very long value"...) be reasonably used instead? What would the field length restrictions be of any such solution?
<input id="someId" type="hidden"
value="5538680,5538683,5538858,5539195,5540063,5540812,5540814,5541665,5541666,5541667,
5541668,5541669,5541670,5541671,5541672,5541673,5541674,5541675,5541676,5541677,5541678,
5541679,5541680,5541682,5541683,5541684,5541685,5541686,5541687,5541688,5541689,5541690,
5541691,5541692,5541693,5541694,5541695,5541696,5541697,5541698,5541728,5543254,5543501,
5543502,5543949,5543950,5544073,5544867,5545079,5545642,5545827,5545890,5545891,5545895,
5545896,5546323,5546631,5546632,5546972,5547794,5547900,5547945,5547980,554923...735181,
5735182,5735183,5735184,5735185,5735187,5735188,5735189,5735227,5735228,5735229,5735235,
5735236,5735237,5735238,5735239,5735240,5735241,5735242,5735243,5735273,5735744,5735745,
5735746,5735747,5735748,5735749,5735836,5735837,5735838,5735839,5735840,5735841,5735842,
5735843,5735844,5735845,5735846,5735847,5735848,5735849,5735850,5735851,5735852,5735853,
5735854,5735855,5735856,5735857,5735858,5735859,5737183,5738250,5738563,5738564,5738565,
5738566,5738567,5738568,5738569,5738570,5738731,5738732,5738946" name="someName">
I'm using ASP.NET MVC 3, and would appreciate a solution that could integrate with a minimum of effort. Ideally, I'd like to be able to pass model values in excess of 1024 characters with razor syntax.
I also need to be able to manipulate the value client-side, using JavaScript/jQuery.
What does everyone do to get around this issue?
Ideally, I'd like to deal with the value as a single variable. Is there a good way to handle such information? The largest value for my usage appears to be about 40k in size.
Edit: If you note the ... in the value of the input element above, it appears that the value is being shortened to 1024 characters, to fit into the value attribute. I'm not positive of the cause of this issue, but believe it to be a limit on the attribute size. If someone can deny this, and/or explain how to allow for a larger attribute or field somewhere, I would greatly appreciate it. I would prefer keeping the re-factoring to a minimum, as I already have a significant investment in the current architecture. A number of other components currently utilize this list of values in it's current form.
Edit: My mistake! Firebug was reporting the "...", and causing JavaScript errors. It apparently doesn't handle attributes in excess of 1024 characters well. All of the data is in fact populating without issue (when firebug is disabled). This appears to be an issue with firebug. I apologize for the inconvenience.
use the grouping
<input name="someIDs[0]" type="hidden" value="5538680"/>
<input name="someIDs[1]" type="hidden" value="5538683/>
update:
controllers
public ActionResult Test()
{
Random rand = new Random();
List<int> list = new List<int>();
for (int i = 0; i < 10000; i++)
{
list.Add(rand.Next(1,999999));
}
return View(list);
}
[HttpPost]
public ActionResult Test(int[] item)
{
return View(item.ToList());
}
view
#model List<int>
#{
ViewBag.Title = "Test";
}
#using (Html.BeginForm())
{
foreach (int item in Model)
{
<input type="hidden" name="item" value="#item" />
}
<input type="submit" value="submit" />
}
How about a
<textarea name="someName">5538680,5538683,...</textarea>
with a style/css rule of display:none applied to it ?
1024 is the limit of any attribute on an HTML element in HTML 3 and below. To get around it, you could use a text area where you put the value in between the tags.
Since you have so much data, you might be better off implementing some sort of paging on the server side and using AJAX to make a request to get the next set of data.
I think the most "correct" way to do this would be using data attributes.
#my-info {
display: none;
}
<div id="my-info" data-ids="id1,id2,etc"></div>
Or through javascript:
<script>
$("#my-info").data("ids", #Model.JsonIds);
</script>
And have Model.JsonIds populated with a Json string.
I would personally go with the second, probably.
I agree with #Gaby about re-thinking the architecture. But if you really must, I suggest you build up javascript array. That way it will be much easier to work with data. it is pretty simple to do this with razor.
i don't really think there is a limit. so long as you can get your string length between the " " quotes, and on the same line, it should accept it. there's rumours of it being 65000 characters, however someone wrote a javascript and got it well over 2,000,000 characters.

Filter Extensions in HTML form upload [duplicate]

This question already has answers here:
File input 'accept' attribute - is it useful?
(8 answers)
Closed 8 years ago.
I have a simple HTML upload form, and I want to specify a default extension ("*.drp" for example). I've read that the way to do this is through the ACCEPT attribute of the input tag, but I don't know how exactly.
<form enctype="multipart/form-data" action="uploader.php" method="POST">
Upload DRP File:
<input name="Upload Saved Replay" type="file" accept="*.drp"/><br />
<input type="submit" value="Upload File" />
</form>
Edit
I know validation is possible using javascript, but I would like the user to only see ".drp" files in his popup dialog. Also, I don't care much about server-side validation in this application.
For specific formats like yours ".drp ". You can directly pass that in accept=".drp" it will work for that.
But without " * "
<input name="Upload Saved Replay" type="file" accept=".drp" />
<br/>
I use javascript to check file extension. Here is my code:
HTML
<input name="fileToUpload" type="file" onchange="check_file()" >
..
..
javascript
function check_file(){
str=document.getElementById('fileToUpload').value.toUpperCase();
suffix=".JPG";
suffix2=".JPEG";
if(str.indexOf(suffix, str.length - suffix.length) == -1||
str.indexOf(suffix2, str.length - suffix2.length) == -1){
alert('File type not allowed,\nAllowed file: *.jpg,*.jpeg');
document.getElementById('fileToUpload').value='';
}
}
The accept attribute expects MIME types, not file masks. For example, to accept PNG images, you'd need accept="image/png". You may need to find out what MIME type the browser considers your file type to be, and use that accordingly. However, since a 'drp' file does not appear standard, you might have to accept a generic MIME type.
Additionally, it appears that most browsers may not honor this attribute.
The better way to filter file uploads is going to be on the server-side. This is inconvenient since the occasional user might waste time uploading a file only to learn they chose the wrong one, but at least you'll have some form of data integrity.
Alternatively you may choose to do a quick check with JavaScript before the form is submitted. Just check the extension of the file field's value to see if it is ".drp". This is probably going to be much more supported than the accept attribute.
The accept attribute specifies a comma-separated list of content types (MIME types) that the target of the form will process correctly. Unfortunately this attribute is ignored by all the major browsers, so it does not affect the browser's file dialog in any way.
I wouldnt use this attribute as most browsers ignore it as CMS points out.
By all means use client side validation but only in conjunction with server side. Any client side validation can be got round.
Slightly off topic but some people check the content type to validate the uploaded file. You need to be careful about this as an attacker can easily change it and upload a php file for example. See the example at: http://www.scanit.be/uploads/php-file-upload.pdf
You can do it using javascript. Grab the value of the form field in your submit function, parse out the extension.
You can start with something like this:
<form name="someform"enctype="multipart/form-data" action="uploader.php" method="POST">
<input type=file name="file1" />
<input type=button onclick="val()" value="xxxx" />
</form>
<script>
function val() {
alert(document.someform.file1.value)
}
</script>
I agree with alexmac - do it server-side as well.
Another solution with a few lines
function checkFile(i){
i = i.substr(i.length - 4, i.length).toLowerCase();
i = i.replace('.','');
switch(i){
case 'jpg':
case 'jpeg':
case 'png':
case 'gif':
// do OK stuff
break;
default:
// do error stuff
break;
}
}