Here is some JS codes I use in forms with onSubmit (so when you send the form, for checking).
Maybe it can help you. If you think my code can be improve, let me know here
If you have ideas to share, tell me too.
If my English is poor, just let me know too
- Replace 123/456/789 for your field ID.
- JS in this box (onSubmit) is loaded when you hit the submit button form, so it's for checking before send to the database.
- To check during editing/adding of the form, or at the init/loading form, please check my other topic here : viewtopic.php?t=4495
- Remember JS can be access with source of the page, so don't use confidential or privacy datas
- alert(''); is for displaying an alert
- .prop('disabled',false); is for re-enabling the submit button after the checking (to able to re-send the form)
- return false; is for prevent the submission
- Regex for a text field (because can't be used with Inputmask field)
Code: Select all
let reg = /^INSERT_YOUR_REGEX_HERE$/gi; //you can check this website for help https://regexr.com/
if(!reg.test($('#fields_123').val()))
{
alert('Error: The field doesn\'t match the format.');
$('.btn-primary-modal-action').prop('disabled',false);
return false;
}
- To compare numeric values
Code: Select all
if(parseFloat($('#fields_123').val()) < parseFloat($('#fields_456').val())) //you can use "<=", ">=", "==", "<", ">"
{
alert('Error: field 123 is lower than field_456.');
$('.btn-primary-modal-action').prop('disabled',false);
return false;
}
- To obtain a good rounded value for a calculation (because sometimes the value can cause bugs)
Code: Select all
var calculation = $('#fields_123').val()*$('#fields_456').val(); //simple fields_123*fields_456 calculation
$('#fields_789').val(Math.round((calculation + Number.EPSILON) * 100) / 100); //get a rounded value and replace the value in the field_789 with it
- To apply a value from a field to another field
Code: Select all
$('#fields_123').val($('#fields_456').val());
- To check if authorization is ok
Code: Select all
var auto = parseInt($('#fields_123').val()); //get an integer number
if (!auto) //check if auto is falsy (0, empty, NaN (not a number, return by parseInt if text), null, undefined, false); you can also use "if ( auto == 0)" to sure auto is 0; or "if (auto)" (truly values : true, not empty, not 0) or "if ( auto != 0)" for auto different of 0
{
$('.btn-primary-modal-action').prop('disabled', false);
alert('Error: Not authorized to send this form.');
return false;
}
- To check if a value from a dropdown list (or another kind of field) is reserved
Code: Select all
var number = $('#fields_123').val();
var tableNumber = ['4567', '8910', '1112', '1314', '1516']; //list of ids of dropdown values
if (tableNumber.includes(number)) //if included in the table
{
$('.btn-primary-modal-action').prop('disabled', false);
alert('Error: this value is reserved.');
return false;
}
- To re-enable a field
Code: Select all
$('#fields_123').prop('disabled', false);
Hope, it will help you