Fomantic Validation Rule and RegExp

172 Views Asked by At

I seem to be hitting my head on a brick wall trying to get a RegExp rule working in the form validation for a field on my Fomantic form. All the other rules work including custom ones; just not a RegExp one.

The regExp rule should be validating that the input field is a valid currency amount, but when I add the rule the page fails to load with - "Failed to load resource: the server responded with a status of 500 (Internal Server Error)". Take the rule out and the page loads fine.

The RegEx is: ^$(\d{1,3}(,\d{3})*|(\d+))(.\d{2})?$

The rule I am defining (after escaping the \ chars) is: -

form_amount: { identifier  : 'form_amount', rules: [
 { type   : "regExp[/^\\$(\\d{1,3}(\\,\\d{3})*|(\\d+))(\\.\\d{2})?$/]", 
   prompt : 'Please enter a valid amount for this transaction' 
 }  
 ] }

Anyone know what I am doing wrong ?

Thanks

Phil

2

There are 2 best solutions below

0
Madhav Bhat K On

Well if you are using JavaScript to validate forms you can do the following

const regex = new Regex('Your Regular Expression')
const result = regex.test('Your currency value') // which will be a boolean value

0
PhilC On

Thanks Madhav that steered me in the right direction. In the end, I realised that the combination of a Smarty template and a RegEx string was not working well together. To avoid any problems, I moved the RegEx string into my PHP and assigned it to a Smarty variable and then used this in the custom validation function in the template. Worked :-)

Extract from the PHP before displaying the template: -

$this->tpl->assign('regcurrency','/(?=.*?\d)^\$?(([1-9]\d{0,2}(,\d{3})*)|\d+)?(\.\d{1,2})?$/');

Javascript in the Smarty Template: -

 $.fn.form.settings.rules.currency = function() {
   let value = ($(".ui.form").form("get value", "form_amount")[0]);
   return {$regcurrency}.test(value);
 };