I need to validate an input field which can contain smarty code or e-mails. I do this with RegExp you can see the code below. The problem is that the e-mail validation removes all the slashes, while the closing tags of a smarty tag ({/foreach}) contain a slash. How can I solve this without removing the slash validation all together?
smarty: function(v) {
var regex = new RegExp("\\{\\{[^\\{^\\}]+\\}\\}", "g");
return regex.test(v);
},
emailOrSmarty: function(v) {
if (this.smarty(v) !== true) {
return this.email(v);
}
return true;
},
email: function(v) {
var regex = new RegExp('^(?:[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~_.\\-+])+@(?:(?:[a-zA-Z0-9\-])+?\.)+(?:[a-zA-Z0-9]{2,})+$');
return regex.test(v);
},
Sample valid input
Example 1 (email):
example@website.com
Example 2 (smarty code):
{{foreach from=$find.users|filter:"male":$city' item='user'}}{{$user.mail}}{{/foreach}}
Your current pattern to match the smarty tags matches the opening and the closing tags. Not sure if that is intended.
If you want to validate if there is only an email address between the smarty tags, you might reuse the smarty pattern by matching the smarty pattern on the input string and then replace with an empty string. That will leave the email address.
Then you could use the email validation to verify the email.
Note that if you don't have escape all the {}
. Your code might look like:
emailOrSmarty: function(v) {
var smartyPattern = /{{[^{}]+}}/g;
return this.smarty(v) || this.email(v.replace(smartyPattern, ""))
}
I have added the same pattern again, but you might move it to another location to be able to reuse it.
If you want to test for either of them, you already have 2 verification functions. For your function you could use an or to return if either of them is true
emailOrSmarty: function (v) {
return this.smarty(v) || this.email(v);
},
To test for the last smarty pattern with {{$user.mail}}
you could add:
smartyMailPattern: function(v) {
var pattern = /{{foreach[^{}]+}}{{\$user\.mail}}{{\/foreach}}/;
return pattern.test(v);
}