问题
I want to validate that a number has certain parameters, for example I want to ensure that a number has 3 decimals is positive. I have searched in different places over the internet, although I could not find how to do it. I have made that text box to accept numbers only. I just need the rest of the features.
Thanks,
$("#formEntDetalle").validate({
rules: {
tbCantidad: { required: true, number: true },
tbPrecioUnidad: { required: true, number: true },
}
messages: {
tbCantidad: { required: "Es Necesario Entrar una cantidad a la orden" },
tbPrecioUnidad: { required: "Es Necesario Entrar el valor valido para el producto" }
},
errorPlacement: function(error, element) {
parent = element.parent().parent();
errorPlace = parent.find(".errorCont");
errorPlace.append(error);
}
});
I want to control that text box with something like:
$.validator.addMethod('Decimal',
function(value, element) {
//validate the number
}, "Please enter a correct number, format xxxx.xxx");
回答1:
Based on the examples here:
$.validator.addMethod('Decimal', function(value, element) {
return this.optional(element) || /^\d+(\.\d{0,3})?$/.test(value);
}, "Please enter a correct number, format xxxx.xxx");
or with commas permitted:
$.validator.addMethod('Decimal', function(value, element) {
return this.optional(element) || /^[0-9,]+(\.\d{0,3})?$/.test(value);
}, "Please enter a correct number, format xxxx.xxx");
回答2:
To prevent that the number can't have decimals, you could use the following:
// This will allow numbers with numbers and commas but not any decimal part
// Note, there are not any assurances that the commas are going to
// be placed in valid locations; 23,45,333 would be accepted
/^[0-9,]+$/
To require always having decimals, you would remove the ? which makes it optional and also require that the digit character (\d) be 1 to 3 digits long:
/^[0-9,]+\.\d{1,3}$/
This is interpreted as match the beginning of the string (^) followed by one or more digits or comma characters. (The + character means one or more.)
Then match the . (dot) character which needed to be escaped with a backslash (\) due to '.' normally meaning one of anything.
Then match a digit but only 1-3 of them. Then the end of the string has to appear. ($)
Regular expressions are very powerful and great to learn. In general they will benefit you no matter what language you run into in the future. There are lots of great tutorials online and books you can get on the subject. Happy learning!
来源:https://stackoverflow.com/questions/10090339/validate-decimal-numbers