Implementing commas and decimals in autonumeric.js - javascript

I have a form which I am trying to get working with autonumeric.js. One of the errors I am getting is that number is not supported by autoNumeric. When I change the input type to text all inputs automatically auto fill to whatever number I am keying in. I am basically trying to start with adding commas and decimals, before i get into currency. I am a little confused as to where to go from here. This is my HTML
<form id="form1">
<h3>Lifetime Value Calculator</h3>
<input value="" type="number" class='num1'/>
<input value="" type="number" class='num2'/>
<input value="" type="number" class='num3'/>
<input value="" type="number" class='num4'/>
</form>
This is my script
var autoNumericInstance = new AutoNumeric('.num1, .num2, .num3, .num4', AutoNumeric.getPredefinedOptions().numericPos.dotDecimalCharCommaSeparator);
$('.num1, .num2, .num3, .num4').on('keyup', function() {
$('.num1, .num2, .num3, .num4').val(autoNumericInstance.getNumericString());
});

I have made some progress. I was able to get commas and decimals for my first input field, but only commas and NO decimals for my last input field, using this script
`
$('.num1, .num4').each(function() {
var autoNumericInstance = new AutoNumeric($(this)[0],AutoNumeric.getPredefinedOptions().numericPos.dotDecimalCharCommaSeparator);
});`
So now I need to figure out why the decimal is not working for my fourth input

What do you want to achieve exactly?
If you want to have 'basic' input with the usual comma as the digit group separator and the dot as the decimal point, then just use:
new AutoNumeric.multiple('#form1 input');
On the other hand, if you only want positive values, use:
new AutoNumeric.multiple('#form1 input', { minimumValue : 0 });
Lastly you were mentioning currency; I would suggest using on the the predefined currency format, and if you do not find yours then 1) ask for it to be included in the AutoNumeric library using the github issues, and 2) just configure it as you wish, for instance like:
new AutoNumeric.multiple('#form1 input', { currencySymbol : '€' });
Do note that you can fiddle with the options pretty easily using the official autoNumeric configurator.

Related

How to only allow the numbers 0-5 in <input> fields with AngularJS?

I have an input field like this:
HTML
<input ng-model="newtodo.effort" ng-enter="addTodo()" type="number" min="0" max="5"
maxlength="1" size="1" step="1" class="form-control marginBottom"
placeholder="Aufwand" aria-describedby="basic-addon2" required></input>
JavaScript/Angular controller
$scope.addTodo(todo) {
restservice.addTodo(todo); // Does call to REST service backend
}
In the input field above I only want to allow integer values 0, 1, 2, 3, 4 and 5.
Not allowed are floats (e.g. 1.4), characters (e.g. foo) and values less than 0 or bigger than 5.
The input field may not be empty!
As you can see I am already using HTML5 input attributes for this but I know that I cannot rely on those. Additionally I also check server-side if the values entered are valid against my restrictions. So far so good, but in order to increase usability and responsiveness of my web app I also want to validate these values in JavaScript using AngularJS. How would I do that? I know that I could implement complicated value checks in $scope.addTodo(todo) and then output error messages to the user if the values he/she entered weren't ok but I somehow "feel" that there is a better, easier "angularish" way using RegEx and a 1-liner? If so, please explain to me how to do this the Angular way. Thanks!
You can add the following attribute to your input field.
ng-pattern="/^[0-5]+$/"
And validate as such:
function formCtrl($scope) {
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="formCtrl">
<form name="myForm">
<input type="number" ng-model="newtodo.effort" name="effort" ng-pattern="/^[0-5]$/" ng-enter="addTodo()" step="1" class="form-control marginBottom" placeholder="Aufwand" aria-describedby="basic-addon2" required>
<span ng-show="myForm.effort.$error.pattern">The number must be between 0-5</span>
<span ng-show="myForm.effort.$error.number">No characters allowed</span>
<span ng-show="myForm.effort.$error.required && !myForm.effort.$error.number">The field is required</span>
</form>
</div>
You can use ngPattern to set the regular expression which you want to validate against.
Reffer to the docs for more details: https://docs.angularjs.org/api/ng/directive/input

Javascript/JQuery how to validate phone number

How to validate input field to enter mobile number and that mobile number should begins with "07" also if some one enter mobile number with space, space should remove on click. . eg: 07 xxxx xxxx onclick it should be 07xxxxxxxx
Now i used html 5 validation method to give warning:
<input type="text" name="mobile_number" required="" title="Number format should be 07xxxxxxxx" pattern="\d{10}">
but this code does not validate it. can someone help me to validate this
When I had to solve the same problem, I used Masked Input Plugin.
You asked me to do it using simple javascript.Here is you answer
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction()
{
var xyz=document.getElementById('mob_no').value.trim();
if(xyz.substr(0,2)==='07')
{
var new_no= document.getElementById('mob_no').value.replace(/\s/g,"")
alert("number after validations check is"+new_no);
}
else
{
alert("incorrect number");
}
}
<input type="text" id="mob_no" name="mobile_number" required="" title="Number format should be 07xxxxxxxx" onblur="myFunction()">
</body>
</html>
Feel free to ask anything and plz repond it worked or not.
Your pattern for accepting telephone number starting with 07 is
<input type="text" name="mobile_number" required="" title="Number format should be 07xxxxxxxx" pattern="^07\d{8}$">
validate 07 at the beginning and after that accept any 8 digit like follow
pattern="^07\d{8}$"
Niles has the right idea.
So, just attach a click handler or a behavior that strips the spaces... ala.
var a = "07989 8989 8 8";
//substitute your element reference ala jQuery('input[name="mobile_number"]');
a = a.replace(/\s+/g,''); // strip the white space
if( /^07\d{8}$/.test(a) ){
// passed test
}else{
// did not pass, show error
}
I believe, like Niles said you would want to use the pattern pattern="^07\d{8}$" which means, in english String starting with "07" ending with any numerical sequence equaling 8 characters
Further more, like James was pointing out, use Javascript to remove your whitespaces. However I would add a interval, to clear them automatically so the user understands how the input works for further usage.
<script type="text/javascript">
var inputElm = document.getElementById('phone_number_id_name'), // id="" name of element
input = inputElm.value;
setInterval(function() { inputElm.value = input.replace(/\s+/g, ''); }, 100); // turncate white-space of input every 100ms
</script>

ng-pattern is not working for number input

I am trying to implement input number field which will allow positive or negative numbers.
I have used "/^0|[1-9]\d*$/" regex expression for ng-pattern.
But it is not working.For character input it is not showing any error.
I have pasted my code here.
Update
I don't want to make this field as required.I just want only number validation(charters are not allowed).
There are a couple of problems with your code:
The pattern /^0|...$/ is interpreted as /(^0)|(...$)/. So, your pattern will accept any string that either begins with 0 (no matter what follows) or ends with any digit in [1-9] (optionally followed by any number of digits).
The correct pattern is: /^(0|[1-9][0-9]*)$/ (note that \d will match more characters than [0-9], e.g. arabic digit symbols etc).
The input elements of type number are handled in the following way by the browser:
If their content is not a valid number, then their value property is set to ''.
Thus, entering 1w3 will cause the value to be an empty string, so then pattern will not be applied.
You should use an input element of type text.
(This is not directly related to your question, but I noticed in your fiddle, you were using <form>.<input>.$invalid, instead of the (probably) intended <form>.<input>.$valid.
$invalid is a property of the FormController only.)
Based on the above, your code should look more like this:
<input type="text" name="price_field" ng-model="price"
ng-pattern="/^(0|[1-9][0-9]*)$/" />
(For accepting negative numbers as well, change ng-pattern to /^(0|\-?[1-9][0-9]*)$/.)
See, also, this short demo.
(UPDATE: The demo has been updated to illustrate the differences between number- and text-fields and between different patterns.)
Why do not use required with min. So we can write:
<div ng-app ng-controller="formCtrl">
<form name="myForm" ng-submit="onSubmit()">
<input type="number"
ng-model="price"
ng-init="price=0"
name="price_field"
min="0"
required
>
<span ng-show="myForm.price_field.$error.required ||
myForm.price_field.$error.min">Not a valid number!</span>
<input type="submit" value="submit" />
</form>
</div>
Demo Fiddle
Howevewr if you still want to use pattern, remove type="number". I'm not sure but sounds like type number has own pattern, this is a reason why it doesn't work.
Here is 2nd Demo Fiddle
used htm5 pattern for input number only
<input type="number" name="country_code" pattern="[0-9]" >
http://www.w3schools.com/tags/att_input_pattern.asp

html & js text field data (DD-MM-YYYY) validation

In my form I have a text field in which user type date. Good habit tells me to not let user to put anything other then dgit and '-' symbol in the field. However i have a bit problem with implementing such feature. So far I Have a field which accept only digits. If user try to put in field letter, this letter is being removed. But the point is to create (DD-MM-YYYY)format so field have to accept '-' symbol. Here is my code:
<input type="text" name="test3" placeholder='DD-MM-YYYY' onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')"/>
i tried put |\- into regex but with no success. Can anyone point me where I am doing mistake?
use thie regex
/^\d{4}-\d{2}-\d{2}$|[^\d-]|-\d{2}-\d*-/
you can also
**/^\d{4}-\d{2}-\d{2}$|[^\d-]|-\d{2}-\d*-/.test(input.value)**
HTML5 has another approach for you:
<input type="date" name="test3">
The browser is responsible for the formatting of the date presentation, though.
You can try something like
<input type="text" name="test3" placeholder='DD-MM-YYYY' onkeyup="if (/[^\d-]/g.test(this.value)) this.value = this.value.replace(/[^\d-]/g,'')" onchange="validate(this)"/>
function validate(el){
var regex = /^(0?[1-9]|[12][0-9]|3[01])-(0?[1-9]|1[012])-\d{4}$/;
if(!regex.test(el.value)){
alert('invalid date');
el.value = '';
}
}
Demo: Fiddle
You can do this with HTML5
see my jsfidle: http://jsfiddle.net/H7tMZ/2/
<form>
<input type="text" name="date" pattern="\d{1,2}-\d{1,2}-\d{4}" placeholder="dd-mm-jjjj"/>
<button type="submit"/>
</form>

Input for percentage values

I have some inputs on my webapp where we're asking the user to enter percentage values (e.g 10.75%, 23%). Currently, they have to enter these values as decimal (e.g. 0.1075 , 0.23).
This is causing confusion for some users, so I was hoping there was a way I could convert the values to and from these formats (the backend has decimal values, the HTML inputs display the percentage values). Is there a solution to this without having to roll-my-own with javascript or the like?
I didn't see anything in the HTML5 inputs that would do this, and I wasn't able to find a javascript lib that would do it easily.
What way have other people been doing percentage inputs in HTML?
Additional Info
The webapp is using Java/Spring, so the values coming to the HTML page are coming string from the java objects in question, so ideally I'm looking for something that doesn't take any backend coding.
Answer
It turns out that Spring 3.0 will do this automatically. Annotating the fields in question with:
#NumberFormat(style = NumberFormat.Style.PERCENT)
private BigDecimal rate;
Will do all the conversion to and from the input field.
The javascript required is very simple. For example you could store the fraction value of the user's input in a hidden field when the user submits.
​<form id="myForm">
<input type="text" id="myPercent" name="myPercent" />%
<input type="hidden" id="myFraction" name="myFraction" />
<input type="submit" />
</form>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
<script type="text/javascript">
document.getElementById('myForm').onsubmit = function() {
document.getElementById('myFraction').value =
document.getElementById('myPercent').value / 100;
}
</script>
It's simple math... 75 to .75 is 75/100. Include a line which converts the numbers after they submitted them.

Categories