Reputation: 2466
This is the fiddle that I tried:
SCRIPT
$(".controlButton").click(function() {
var SHPname = $(this).closest('.row').find('.fname').val();
var textfieldmask = /^\s*-?[1-9]\d*(\.\d{1,2})?\s*$/;
/// check full name
if (SHPname.length > 0){
var testname = textfieldmask.test(SHPname);
alert (testname);
if (testname == true ){
var tstnm = "ok";
alert (tstnm);
} else {
alert ("Enter digits up to 2 decimal places!");
$('#fname').focus();
return false;
}
} else {
alert ("Please enter price");
$('#fname').focus();
return true;
}
});
HTML
<div class="row">
<label class="required" for="name" title="Enter your name"><input type="text" id="fname" class="fname" name="fname" />Price</label>
<label for="formsubmit" class="nocontent"><a class="controlButton" href="#" class="progress-button"><p id="BTNtxt">Save</p></a>
</div>
</label>
But this doesn't apply the rule I wanted: Please help me to modify this to match this rule below:
RULE: to only allow numbers (up to 4 digits) to 2 decimal places
Upvotes: 1
Views: 348
Reputation: 626845
RULE: to only allow numbers (up to 4 digits) to 2 decimal places
However, your current regex also lays another restriction: the integer part cannot start with a zero.
Thus, you can use
/^\s*-?[1-9][0-9]{0,3}(?:\.[0-9]{1,2})?\s*$/
^^^^^^^^^^
Regex demo (here, the first digit in the integer part can be in the range from 1 to 9, and there can be 0 to 3 other digits after it.)
This expression requires at least 1 digit in the integer part! (it does not allow -.55
)
Or
/^\s*-?(?!0)[0-9]{0,4}(?:\.[0-9]{1,2})?\s*$/
^^^^^^^^^^^^^^^
Regex demo (here, the integer part can include 4 digits but the first one cannot be 0
due to the negative lookahead (?!0)
).
This expression DOES NOT require at least 1 digit in the integer part! (it allows -.55
)
See your updated fiddle
Since lookarounds make regex patterns less efficient (it can be seen if you test both the patterns in regex101.com using PCRE
or Python
settings), I'd choose the first regex. However, based on your further requirements, you may choose the second pattern.
Upvotes: 1