This could help you:
/^(\d*(?:\.\d+)?)/
^ // anchor for start of string
( // start of capture group, indicates start of string of interest
\d* // allows zero or more digits before point
(?:\. // first point
\d+)? // allows one or more digits after point optionally
) // end of capture group
You can get the capture string using $1
I have (?:\d+)?
on my regex to handle 2.
cases.
Demo
EDIT: If you want to accept only .
's and digits after the string of interest you can use. It will reject any string that contains any character that is not inside []
^(\d*(?:\.\d+)?)[\.\d]*$
I only added
[\.\d]*$
it only accepts .
's and digits until the end of the string,
Demo
EDIT: Below snippet show my regex in action. I have used your code as base. I believe that you can adapt to your need.
$(document).ready(function() {
var value = [$("#valid").html(), $("#invalid").html()]
var regex = /^(\d*(?:\.\d+)?)[\.\d]*$/
for(var i=0; i < value.length; i++) {
if (value[i].match(regex)) {
var result = value[i]+" is valid - "
result += "Replace:" + value[i].replace(regex, '$1') + "\n";
$("#result_valid").append(result)
} else {
var result = value[i]+" is invalid\n"
$("#result_invalid").append(result)
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=valid>12.1.1</div>
<div id=result_valid></div>
<div id=invalid>abc12.1.1</div>
<div id=result_invalid></div>
EDIT: Regarding OP's comments and needs to evaluate string for each char entered in "realtime", I have to change the regex to a more permissive one
/^(\d*\.?\d*)[\.\d]*$/
var regex = /^(\d*\.?\d*)[\.\d]*$/
$("#spot_size_value").bind("change keyup input", function (e) {
if (this.value.match(regex)) {
this.value = this.value.replace(regex, '$1');
} else{
this.value = ""
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="col-md-2 control-label" for="spot_size">Spot Size</label>
<div class="col-md-6">
<input id="spot_size_value" name="spot_size_value" type="text" placeholder="" class="form-control input-sm">
<div class="validation_error" id="error_spot_size"></div>
</div>