Excellent question!
You don't need jQuery for this. You can do this with the built-in Magento form validator. First the javascript to set up the form for validation must be placed in your form template:
<script type="text/javascript">
var myForm= new VarienForm('[your form id]', true);
</script>
Now prepare your form fields by adding the appropriate css classes.
Cannot have number greater than 9.99
<input type="text" class="required-entry validate-digits-range digits-range-0-9.99"/>
No spaces in the fields
<input type="text" class="required-entry validate-alphanum"/>
That's it! For the more specific use cases you'll have to add custom validation rules:
Only number fields need to have .00 to validate 1 to 1.00
Validation.add('validate-float','Input must be in the form of 0.00',function(v){
return Validation.get('IsEmpty').test(v) || (!/\./.test(v));
});
Which then is validated with the following:
<input type="text" class="required-entry validate-float"/>
Letters need to be uppercase
This one is similar, the regex must test for a range of uppercase:
Validation.add('validate-uppercase','Input must be in uppercase',function(v){
return Validation.get('IsEmpty').test(v) || (!/^[A-Z]+$/.test(v));
});
And used like:
<input type="text" class="required-entry validate-uppercase"/>
Basically, you need to register your custom validation method and then use it for your field in system.xml
file.
Define your validation method:
jQuery.validator.addMethod(
"validate-custom",
function (v) {
return jQuery.mage.isEmptyNoTrim(v) || /^[1-4]+$/.test(v);
},
'Please use digits only (1-4) in this field.'
);
And use it for your field in system.xml
:
<validate>validate-number validate-zero-or-greater validate-custom</validate>
Search for "validator.addMethod" in the Magento 2 core code, there are a bunch of examples there showing more complex use cases.
Best Answer
I wanted a to add a custom rule with custom error message, I achieved it using:
Worked fine.