Test a String Contains [A-Z], [a-z] or [0-9] in Server Action

Is there a straightforward way to test a string in a Server Action to check it only contains [A-Z], [a-z] or [0-9]?

Hello, when/how is this string supposed to be checked?

I just want to do a condition in a server action which says:

if this_string only contains [A-Z], [a-z] or [0-9]
   do_this
else
   do_that

So if the string contains characters like + = - then the condition fails and we do_that.

What I am actually trying to do in a server action is create a random string that is made from
[A-Z], [a-z] or [0-9]. The best way I can find to do this is with the following code:

id16

But sometimes I get a non [A-Z], [a-z] or [0-9] character.

If you have a better way to create such a random string in a server action I’d love to hear about that!

You should probably consider a custom formatter and you could avoid the check altogether.

Something in these terms:

<?php

namespace lib\core;

function formatter_id16() {
$allowed_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
return substr(str_shuffle($allowed_chars), 0, 16);
}
 

Then

Set Value id16 = {{ id16() }}

I actually haven’t tried a custom formatter without parameters so I don’t know if this will work. If not just pass a dummy string as $val.

What is you use case? What does that string accomplish?

1 Like

Thanks for that input @JonL!

I’m not at all familiar with the PHP world so would prefer to avoid it if I can… but I’ll go that way if I have to I guess!

It creates a unique id for contacts and events that can be safely passed outside the system… a bit like your booking id when you book with Ryanair!

Why not use uuid4 then? Seems like that is what you need. My custom formatter is shit if you need unique ids. But you only mentioned that in your last reply.

All in all I would go with uuid4. You can also build a custom formatter for that.

Anyway…answering your OP. You need a custom formatter.

<?php

namespace lib\core;

function formatter_isValidID16($val) {

preg_match('/[^A-Za-z0-9]/', strval($val), $result);
return empty($result);
}

Then in your if condition just check {{ id16.isValidID16() }}

But you are reinventing a big wheel and building it square shaped :wink: