This question already has answers here:
Simple regular expression for a decimal with a precision of 2
(17 answers)
Closed 9 years ago.
i Want to validate a text field in keyup event .
in the field it should accept money type decimal like
(12.23)
(.23)
(0.26)
(5.09)
(6.00)
if i enter some wrong value then it should return to the previous value and remove the wrong one
I think something like this might be your best bet
var isValidCurrency = function(str) {
var num = parseFloat(str);
return !Number.isNaN(num) && num.toFixed(2).toString() === str;
};
Some tests
isValidCurrency("1234.56"); // true
isValidCurrency("1234.565"); // false
isValidCurrency("1234"); // false
isValidCurrency("foo"); // false
You can use following Regex
val = "2.13"
if (!val.match(/^(\d{0,2})(\.\d{2})$/)) {
alert("wrong");
} else {
alert("right");
}
http://jsfiddle.net/rtL3J/1/
EDIT
Please note that if the numbers preceding dot (.) has limit of length to two then the code valid code is
^(\d{0,2})(\.\d{2})$
else if there is no limit then just remove the 2 from the code i.e.
^(\d{0,})(\.\d{2})$
Try this:
function evMoneyFormat(evt) {
//--- only accepts accepts number and 2 decimal place value
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /^[0-9]{1,14}\.[0-9]{0,2}$/; // number with 2 decimal places
if (!regex.test(key)) {
theEvent.returnValue = false;
//--- this prevents the character from being displayed
if (theEvent.preventDefault) theEvent.preventDefault();
}
}
The control:
<input type='text' onkeyup='evMoneyFormat( e );'>
Try following code
function validateDecimal(num){
var dotPosition=num.indexOf(".");
if(dotPosition=="-1"){
document.getElementById('cost').value= num+".00"
}
}
And in html
<input type="text" id='cost' onkeyup="validateDecimal(this.value)" />
Related
This question already has answers here:
Decimal or numeric values in regular expression validation
(13 answers)
Closed 2 years ago.
I have an input field I want the input value to be only numbers and decimals nothing more but the problem is that when I type the Unicode characters and letters and semicolons the input value excepts it how do I achieve that.
let newValue = item.value.replace(new RegExp(/[a-z] && [#!#$%^&*()_+}{}|:,=] /,'ig'), "");
item.value = newValue;
If you want to only accept number and decimals for your input you can do either of these two ways:
Use input type number.
<input type="number"/>
Use a regex like below, which accept only numbers and decimals:
^-?[0-9]\d*(\.\d+)?$
NOTE: If you want to use the comma (and . in any place) as input also, you can use this one (according to this post):
^-?[0-9][\.\d]*(,\d+)?$
Update
Validation on input:
var org = '';
document.getElementsByTagName('input')[0].oninput = function(e) {
var val = document.getElementsByTagName('input')[0].value;
if(val == '' || val.match(/^([0-9]*\.)?[0-9]*$/)) {
org = val;
} else {
val = org;
}
document.getElementsByTagName('input')[0].value = val;
}
document.getElementsByTagName('input')[0].oninput();
Number here: <input value="1.23" type="text" /><br />
function scrubInput() {
let numberInputElem = document.getElementById('numberInput');
const regex = /[^0-9\.]/
let newValue = numberInputElem.value.replace(regex, "");
numberInputElem.value = newValue;
}
<input type="text" id="numberInput" oninput="scrubInput()"/>
I have a simple if statment in a verify function that check at least 10 numbers are used in a field
function verfiyFields() {
var flag = true;
var number = $atj('#interested-number-form');
if(number.val().replace(/\s+/g, '').length < 10){
number.parent().prepend('<p class="form-error">Please enter phone number</p>');
fadeOut();
flag = false;
}
return flag;
}
How can I also check that only numbers are used.
You could use .match(/^\d+$/) to check if there are only digits.
var value = number.val().replace(/\s+/g, '');
if (value.length >= 10 && value.match(/^\d+$/)) {
// ..
}
You can also check if there are at least 10 digits using the regular expression /^\d{10,}$/ and avoid checking the length property:
var value = number.val().replace(/\s+/g, '')
if (value.match(/^\d{10,}$/)) {
// ..
}
As a side note, you can also use the pattern attribute:
<form>
<input type="text" pattern="^\d{10,}$" />
<input type="submit" />
</form>
function verfiyFields() {
var reg = /^\D*(?:\d\D*){10}$/;
var number = $atj('#interested-number-form');
var flag = reg.test(number.val())
if (!(flag)) {
number.parent().append('<p class="form-error">Please enter a valid 10 digit phone number</p>');
}
return flag;
}
Use RegExp.test(str) to check to make sure that the length of the field excluding all characters that are not digits is 10. RegExp.test returns a true or false value so this can be the flag you return.
RegExp.test(str) Documentation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
Demo:
http://jsfiddle.net/SeanWessell/1v6vnath/
I called a class called test for my textbox. When I entered the first value for e.g. the first value as 4., then suddenly the output coming as 4.00. I just want to restrict entry only for two decimal places.
$(".test").keyup(function (event) {
debugger;
this.value = parseFloat(this.value).toFixed(2);
});
This small change to your code may suffice:
this.value = this.value.replace (/(\.\d\d)\d+|([\d.]*)[^\d.]/, '$1$2');
Essentially replace the decimal point followed by any number of digits by a decimal point and the first two digits only. Or if a non digit is entered removes it.
What about something like this:
$(".test").keyup(function (event) {
if ((pointPos = this.value.indexOf('.')) >= 0)
$(this).attr("maxLength", pointPos+3);
else
$(this).removeAttr("maxLength");
});
Here is a working fiddle.
you can use the maxLength attribute for that, try
$(".test").keyup(function (event) {
var last = $(this).val()[$(this).val().length - 1];
if (last == '.') {
$(".test").attr("maxlength", $(this).val().length+2);
}
});
You shouldn't worry about what the user has in the input until they submit the form. You really don't care what's in there before then. However, if you want to warn about invalid input, you can put a message on the screen if you detect non–conforming input, e.g.
<script>
function validate(element) {
var re = /^\s*\d*\.?\d{0,2}\s*$/;
var errMsg = "Number must have a maximum of 2 decimal places";
var errNode = document.getElementById(element.name + '-error')
if (errNode) {
errNode.innerHTML = re.test(element.value)? '' : errMsg;
}
}
</script>
You should probably also put a listener on the change handler too to account for values that get there by other means.
$(document).on("keyup", ".ctc", function ()
{
if (!this.value.match(/^\s*\d*\.?\d{0,2}\s*$/) && this.value != "") {
this.value = "";
this.focus();
alert("Please Enter only alphabets in text");
}
});
I have a JavaScript function that validates an input field and prevents the user from typing anything that doesn't match the condition. This function is based on event.keyCode.
I'm trying to modify the function to use a RegExp and validates not "per character" but "per whole input" so that it does the same, but with different conditions:
numeric only
allowed decimal "." or ","
Here is the function in its current form, using event.keyCode:
function isNumeric(evt, alertDIVid, alertMsg) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode >= 48 && charCode <= 57) {
document.getElementById(alertDIVid).innerHTML = '';
return true;
}
else {
document.getElementById(alertDIVid).innerHTML = alertMsg;
return false;
}
}
document.getElementById('AMNT').onkeypress = function(event) {
event = event || window.event;
return isNumeric(event, 'numericalert', 'Numeric values only!')
};
In order to do the kind of validation you want, you need to listen to the keyup event instead. This event fires after the field is changed, so that you know the new value of the field. You also need to know the previous value of the field so you can "reset" it if what the user typed turns out to be invalid.
For example:
(function() {
var previousValue = document.getElementById('myInput').value;
var pattern = /^\d*((\.|,)\d*)?$/;
function validateInput(event) {
event = event || window.event;
var newValue = event.target.value || '';
if (newValue.match(pattern)) {
// Valid input; update previousValue:
previousValue = newValue;
} else {
// Invalid input; reset field value:
event.target.value = previousValue;
}
}
document.getElementById('myInput').onkeyup = validateInput;
}());
Working demo: http://jsfiddle.net/8kUdG/
It's worth noting that this will also validate empty strings, as well as unfinished numbers, like 5, or 42. (otherwise the user would have to insert the decimal sign after typing the decimals, which would be... weird).
And finally, keep in mind that this might not be a cross-browser safe solution. If you need a pure-JavaScript solution, you will need to refine it (i.e., this might not work in IE).
Edit: of course, showing an error message instead of resetting the input field to the previous value is also perfectly possible (updated JSFiddle):
(function() {
var pattern = /^(?=.)\d*(?:[.,]\d+)?$/;
var error = document.getElementById('error');
document.getElementById('myInput').onkeyup = function(event) {
event = event || window.event;
var newValue = event.target.value || '';
if (newValue.match(pattern)) {
error.innerHTML = '';
} else {
error.innerHTML = 'Not a valid number!';
}
};
}());
I leave it up to you to replace the alert with something more user-friendly.
The easiest solution would be something like this
// Returns true on valid, false on invalid
function myInputFilter(input)
{
var value = input.value;
var regex = /^[\d\,\.]*$/;
if(!regex.test(value))
return false;
return true;
}
You could edit the function to just take a string argument, but I've chosen to have it accept the text input element instead. The RegEx can be replaced by anything, I've made a simple one for this example. I would refine it a bit if I were you (You can use the excellent online tool RegExr)
Here is an example of the filter implemented
http://jsfiddle.net/kVV77/
You can use following regular expression:
/^[+-]?(?=.)(?:\d+,)*\d*(?:\.\d+)?$/
to allow only any number of comma and only one dot . with the condition that number cannot start with a comma. Number can have optional + or - at the start.
I was trying to make a javascript function which will check if the user entered value inside a text field cannot be less than 9 digits & it cannot be all 0s.
This is what I made
function CheckField(field)
{
if (field.value.length <9 || field.value=="000000000")
{
alert("fail");
field.focus();
return false;
}
else
{
return true;
}
}
<input type ="text" id="number1" onBlur='return CheckField(this)'>
But this doesnt check the condition where user enters more than 9 values and all 0's. It checks only for 1 condition that is with exact 9 zeros 000000000
So, if I understand that right you want the user to be able to enter a number with more than 9 digits, but they cannot be all zeros, right?
This can be done with a regexp:
var value; // Obtain it somehow
if (/^\d{9,}$/.test(value) && !/^0+$/.test(value)) {
// ok
}
What this checks is whether the value is at lest 9 digits (it does not allow anything but digits) and that they are not all 0s.
This should check for both conditions:
function CheckField(field){
return !/0{9}/.test(field.value) && /\d{9}/.test(field.value);
}
Try something like this:
var valueEntered = field.value;
if (parseInt(valueEntered) == 0) ...
or if you wanted to check if it was a number as well:
if (!(parseInt(valueEntered) > 0))
Two options spring to mind. You can try parsing the value as a number and test for isNaN or != 0
var parsed = parseInt(field.value, 10);
if(field.value.length < 9 || !(isNaN(parsed) || parsed != 0)){
alert("fail");
... rest of code
}
Or you could use a regex
if(field.value.length < 9 || !/[^0]/.test(field.value){
alert("fail");
... rest of code
}
The first option is probably quicker.
try this:
if (field.value.length <9 || field.value.replace("0","") == "")