I have some client-side validation against a text box, which only allows numbers up to two decimal places with no other input.
This script was a basis for entering n
Do you really want to do this with a regex?
function valid(f) {
if(isNaN(f)){return false;}
return 100 * f == parseInt(100*f,10);
}
gs: This is very close, but the line
f.value = f.value.replace(/[^\d\.]/g, "");
Doesn't actually appear to work. In fact I lose focus of the text box for some reason. Although perhaps it's my code ;)
The . character has special meaning in RegEx so needs escaping.
/^(?:\d*\.\d{1,2}|\d+)$/
This matches 123.45, 123.4, 123 and .2, .24 but not emtpy string, 123., 123.456
.
means in RegEx: any character, you have to put a backslash infront of it. \.
This would be better:
/^\d+(\.\d{0,2})?$/
Parts I included:
+
with *
but then also empty strings would be matched.$
stands for the end of the input.and for the replacing part you should also include the dot
f.value.replace(/[^\d\.]/g, "")
Edit:
If it's for the live validation of inputs, why don't you just either intercept keyevents and test for their validity (by creating the string in memory) or just delete the last character in the field?
/^\d+(\.\d{1,2})?$/
function valid(f) {
if(!f.value) { // Test if text field is empty
f.value = 0; // Initialize value to 0
console.log("Valid number"); // Let user know input is OK
} else if (!/^\d+(\.\d{1,2})?$/.test(f.value)) { // Test regex
f.value = ""; // Empty the text box
console.error("invalid number"); // Let user know input is not OK
} else {
console.log("Valid number"); // Let user know input is OK
}
}
document.getElementById("testbutton").addEventListener( // Add event listener to button
"click",
valid.bind( // Bind the text field to the `value` function
this,
document.getElementById("testfield")
)
);
<input id="testfield" value="15.1" />
<button id="testbutton">Test expression</button>
/ /
: the beginning and end of the expression^
: whatever follows should be at the beginning of the string you're testing\d+
: there should be at least one digit( )?
: this part is optional\.
: here goes a dot\d{1,2}
: there should be between one and five digits here$
: whatever precedes this should be at the end of the string you're testingYou can use regexr.com or regex101.com for testing regular expressions directly in the browser!
If we need to validate numric value in a textbox where we want to prevent more than one decimals(e.g 2..3,.2. etc)
Below is the Javascript funcion for that.
if (MoreThanOnePoint(document.getElementById("txtNoofHrs").value) == false) {
alert("Please enter one decimal only");
document.forms[0].txtNoofHrs.focus();
return false;
}
function MoreThanOnePoint(strString) {
var strChar;
var blnResult = true;
var varcount = 0;
for (i = 0; i < strString.length && blnResult == true; i++) {
if (strString.charAt(i) == ".") {
varcount++;
if (varcount > 1) {
//alert("Please enter one decimal only");
blnResult = false;
}
}
}
return blnResult;
}