I use jQuery Validation Plugin to perform client side form validation. It works well. However, I don't know precisely Regex and I'm not able to achieve what I want.
I would like to add 3 different Regex in order to display 3 different messages depending on what the user enter in input field.:
- Regex 1 detect if it is not a number with a specific message
- Regex 2 accept dot or comma for decimal with a specific message
- only 2 numbers for decimal after dot or comma with a specific message
There are plenty of questions related but I've tried a lot of answers on SO which don't work well.
Here is a working snippet
jQuery.validator.addMethod("decimal", function(value, element) {
// Validating Decimal Numbers
return this.optional(element) || /^([0-9]+[.]?[0-9]?[0-9]?|[0-9]+)$/g.test(value);
}, 'Please enter only numbers (format 0.00)');
jQuery.validator.addMethod("two_decimal", function(value, element) {
// require 2 decimals
return this.optional(element) || /^((d+(\.d{0,2})?)|((d*(.d{1,2}))))$/.test(value);
}, "Pleaser enter 2 numbers after dot");
// https://jqueryvalidation.org
$("#test_form").validate({
submitHandler: function(form) {
form.submit();
},
// rules, options, etc.,
onkeyup: function(element) {
// "eager" validation
this.element(element);
},
rules: {
decimal_number: {
required: true,
minlength: 1,
maxlength: 10,
decimal: true,
two_decimal: true
}
},
messages: {
montant_demande: {
required: "Please enter a number",
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.min.js"></script>
<form class="cmxform" id="test_form" method="get" action="">
<fieldset>
<legend>Test</legend>
<p>
<label for="decimal_number">Number decimal</label>
<input id="decimal_number" name="decimal_number" minlength="2" type="text" required>
</p>
</fieldset>
</form>
question from:
https://stackoverflow.com/questions/65834789/set-regex-for-only-2-decimal-numbers-dot-comma-with-jquery-validator-plugin 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…