Validate clock time with quarters - javascript

I want to match below in a text box when user entered values.
.00
.25
.50
.75
and 2 specific digits:
[0 to 23].00
[0 to 23].25
[0 to 23].50
[0 to 23].75
for example 1.25, 12.25, 22.50, etc. All above values are allowed.
Values like 0, 7, 12.18, 24.00 are not allowed.
Currently I am just checking below which will allow any decimal values.
var charCode = (e.which) ? e.which : event.keyCode
if (
(charCode != 46 || $(element).val().indexOf('.') != -1) &&
(charCode < 48 || charCode > 57)
) return false;
return true;

Validate clock time with quarters
Thanks to the comments section we all realized it's a validation of a clock time (question edited to reflect).
Glad to remind here that in such case .00 or either 0.00 — should be a valid input since it represents midnight. And therefore all other integers of full-hour like 1.00 up to 23.00 are also valid.
Don't use keyboard Events. As #trincot suggested, if a user enters ".2" he will no longer be able to finish the desired number (0.25) since ".2" is (per your statement) already invalid.
Instead, use rather a "blur" or some other event. Or you can also use the Input element pattern attribute to visually mark the input as invalid.
Here's the basic regex to match the desired: a clock time with quarters
^(\d|[0-1]\d|2[0-3])?\.(00|15|30|45)$
or if you use decimals as hundreds:
^(\d|[0-1]\d|2[0-3])?\.(00|25|50|75)$
Regex101.com demo and explanation
Example of input pattern attribute:
input:invalid { background: red; }
<input type="text" pattern="(\d|[0-1]\d|2[0-3])?\.(00|25|50|75)">
Example using RegExp.prototype.test() ideal for JS validation
const validateNumDec = n => /^(\d|[0-1]\d|2[0-3])?\.(00|25|50|75)$/.test(n);
console.log(".00", validateNumDec(".00")); // true
console.log(".25", validateNumDec(".25")); // true
console.log("13.00", validateNumDec("13.00")); // true
console.log("23.75", validateNumDec("23.75")); // true
console.log("5", validateNumDec("5")); // false
console.log("5.13", validateNumDec("5.13")); // false
console.log("5.13", validateNumDec("23.59")); // false
Final note
One might eventually simply go for <input type="time" but as you can see the step="900" (900 seconds being 15 minutes) do work when using i.e: keyboarrd's up/down arrows (15 min jump), but it's not respected in the popup picker — in Chrome browser:
<input type="time" min="00:00" max="18:00" step="900" required>
From the MDN documentation about Using the Step attribute:
Note:
Using step seems to cause validation to not work properly (as seen in the next section).
Documentation:
RegExp.prototype.test()
Pattern attribute

Related

How to make an input box to accept positive and negative decimal values?

How can I make an input box to accept only one - sign OR one + sign AND one decimal point with numbers?
I tried `preventDefault(); to block other characters by following code:
$('.pndecimal').on('keypress keyup blur', function(e){
if(e.which< 48 && e.which > 57)
{
e.preventDefault();
}
});
I'm not able to allow these because they are out of range of ASCII codes of numbers (e.which<48 & e.which >57)
Use regular expression validation, if it passes take the value or else show error.
eg: /(-|\\+)+[0-9]+\\.[0-9]+/g
valid inputs: +9.0, -9.7, +78.9, -10.0
If you want to have more than one number after decimal point than use this pattern(this patterns also allow inputs like -99/,++,--)
eg: /(-|\\+)+[0-9]+\\.[0-9]+/g
valid inputs: +91.42, +1.809, -9.0
If you want to restrict to 2 integer numbers,2 decimal numbers,any one sign use the following:
RegExp(/(-|\+)+[0-9]+\.[0-9]+/g)
<input type="text" maxlength="4">

toString().length on a number with zeros and only zeros always returns 0

I'm working on a page that accepts 4 digits (exactly 4 digits) pin from users. Something like this.
<input type="number" ng-model="passCode" class="form-control" onpaste="return false" id="passCodeField" ng-disabled="!enablePassCode" ng-change="onInputPasscode()" ng-keypress="onKeyPressPasscode($event)"/>
onKeyPressPasscode function
$scope.onKeyPressPasscode = function($event) {
if(isNaN(String.fromCharCode($event.which || $event.keyCode))){
$event.preventDefault();
}
}
onInputPasscode() function :
$scope.onInputPasscode = function() {
if ($scope.passCode.toString().length > 4){
$scope.passCode = $scope.passcode;
}
if($scope.passCode.toString().length == 4) {
$scope.passcode = $scope.passCode;
$scope.disableContinue = false;
session.put('pinFlow',true);
} else {
console.log("current length - " + $scope.passCode);
$scope.disableContinue = true;
session.put('pinFlow',false);
}
}
This is failing when the input is all zeros. i.e current length is not getting updated hence the user is allowed input as many zeros as he wants. How do I take 4 digit zeros as input and still meet the checks that I have?
This is in angular 1.5.8v. And I'm not an expert in AngularJS. So any help would be appreciated. Also, please let me know if need any other info. I'll update the answer accordingly.
Thanks in advance.
It's not possible to do this with a an input with type set to number.
When user enters a number 0001, that's actually 1.
Things like PINs should be handled with type set to text.
You can then use a regex for validation.
To allow exactly four digits, no more and no less, use the following regex:
^\d{4,4}$
From JavaScript, use this regex to test a string, like the following:
/^\d{4,4}$/.test('1234')
// => true
/^\d{4,4}$/.test('123456')
// => false
/^\d{4,4}$/.test('12')
// => false
The cause of your problem is that if you PIN Scheme allows for leadings zeros, number is not the ideal type for this (because in numbers, leading zeros can be omitted without changing meaning).
Instead, use input type=text or probably even better, input type=password. Also, I wouldn't listen to keypress - instead use the input event.

how to make a text field to accept only numbers, and two decimal places

I need to make a text field accept only numbers and decimal point, and default to two decimal places.
I got this code from a search here. It works for accepting only numbers.
I need to make it accept decimal point, and default to two decimal places.
<input type="text" onkeypress="return event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode));" />
Thanks
You could use a regular expression to limit what can be entered into the field.
As an example:
<input type="text" pattern="(?:[01]|2(?![4-9])){1}\d{1}:[0-5]{1}\d{1}">
You can visit a site like regexlib.com which can help you build and test the type of regex you are seeking.
There may be a better or more eloquent method, but this easy and works for me.
Leave it to HTML5:
<input type="number" step="0.01">
Also, remember about server side validation (in PHP for example). Don't try to force some missing keypress, or don't override default browser behaviour. This is not user friendly.
What will you do if you press A, and nothing is displayed? Would you go to a shop for a new keyboard?
In that case try to give the user a clue, what type of data you expect.
Give the user a tool (type="number") to show best possible keyboard layout on the phone.
But don't try to do it "better". In that case it means worse.
More on the subject:
Is there a float input type in HTML(5)?
If you want to always show 2 decimal places, you can reformat the input on change to round and display to 2 decimals:
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode > 31 && (charCode != 46 && (charCode < 48 || charCode > 57)))
return false;
return true;
}
$("#twodecimals").change(function() {
var format = parseFloat(Math.round($(this).val() * 100) / 100).toFixed(2);
$(this).val(format);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="twodecimals" onkeypress="return isNumberKey(event)" />

p:inputtext format number like '999,999'

In my XHTML page I have some inputText fields where the user can insert numeric values in the format "999,999" (max three integer values, max three decimal values). The decimal separator is ",", because I want to format the above fields using the Italian locale.
Actually this is my p:inputText component:
<p:inputText value="#{r.value}" id="verog_#{r.id}"
onkeypress="return isNumberKey(event)" />
The isNumberKey() javascript function enables permitted characters only (numbers and comma):
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode == 44) return true;
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
But I have no control on the maximum number of digits allowed, so the user can, for example, input a number like "1234,5678", or, even worse, "12,,34".
I need to check these values on the client side because they are within a dialog. Actually I make checks on the server side, after the "save" button is clicked:
<p:commandButton value="save" action="#{myBean.saveAction}" ajax="true"
update=":growl" oncomplete="dialogVar.hide()">
<f:param name="action" value="#{action}" />
</p:commandButton>
But if I have an input error, the dialog is always hidden, and the user is forced to submit the values again.
I cannot use f:convertNumber, because data are saved on the db as strings, not as numbers.
I also tried to use the p:inputMask component, but I cannot make it to work properly (maybe for a lack of knowledge): the mask "999?,999" does not fit my requirements.
Maybe I can do it using a converter (the p:inputText component has the "converter" and "converterMessage" attributes), but my converter attempts failed too:
NumberFormat nf = NumberFormat.getNumberInstance(Locale.ITALIAN);
nf.setMaximumIntegerDigits(3);
nf.setMaximumFractionDigits(3);
String result = nf.format(submittedValue);
It always gives me IllegalArgumentException, even if submittedValue is 0.
How can I reach my goal? Thanks in advance.
You need to test the whole value on the client side.
I've made a fiddle with example JS validation: http://jsfiddle.net/lechlukasz/w8K8j/1/
It calls validation function on blur:
function valid(val) {
var reg = new RegExp('^[0-9]{1,3}(,[0-9]{1,3})?$');
if (!reg.test(val))
return false;
return true;
}
If you want to make full validation on keypress, don't forget to allow the coma as the last character (illegal in final string, but necessary when typing :)

Check string for integer

I want to validate a input field. The user should type in a phone number with minimum length of 10 digits.
So I need to check for illegal chars. It would be nice just to check wheather the input is an integer or not.
I came up with this but it does not work (n would be the string).
function isInt(n){
return typeof n== 'number' && n%1==0;
}
Any ideas?
You can do a test like this:
input.length >= 10 && /^[0-9]+$/.test(input)
That will fail if there are non-digits in the string or the string is less than 10 chars long
This should work((input - 0) automatically tries to convert the value to a number):
function isInt(input){
return ((input - 0) == input && input % 1==0);
}
There is already an SO-question about this issue: Validate decimal numbers in JavaScript - IsNumeric()
Might be an overkill for you, but Google has not too long ago announced a library for phone validation. Java and Javascript variants are available.
Validating a phone number is a little more complicated than checking if the input is an integer. As an example phone numbers can and do begin with zeros so it isn't technically and int. Also users may enter dashes: For example:
00 34 922-123-456
So, as for validating it you have a couple of options:
Use regex expression to validate, have a look at:
http://regexlib.com/
this site will have hundreds of examples
Use looping to check each characters in turn, i.e. is character int or dash
I would recommend the former as the latter depends on consistent input from users and you aren't going to get that
Why not use:
return (+val === ~~val && null !== val);
as a return in your function?
this is the output of the javascript console
> +"foobar" === ~~"foobar"
false
> +1.6 === ~~1.6
false
> +'-1' === ~~'-1'
true
> +'-1.56' === ~~'-1.56'
false
> +1 === ~~1
true
> +-1 === ~~-1
true
> +null === ~~null // this is why we need the "&& null !== val" in our return call
true

Categories

Resources