Validating a form field with several emails

I'm trying to create a validation in the backend, of an email field that must have 1 or more emails, separated with the “;” character. To do this I was trying to use the following javascript inside a “Set Value” component:

(emails_input.trim() == '') || (emails_input.split(';').map(x => x.trim()).filter(x => x != '').length > 0 && emails_input.split(';').map(x => x.trim()).filter(x => x != '').every(x => x.isEmail()))

But Wappler can't recognize the code...what's wrong with my code?


Thank you for your help

Not sure a set value can deal with .js like that.

Solution depends on the level of validation you need,

Obviously split in ";" returns an array so the length would indicate the number of components.
A simple check that each element contains the "@" character would be a simple check as to basic validity.

Past that i would be tempted to write a custom module/ formatter to do a fuller validation.

I was trying to follow your suggestion and created a custom formatter to do the validation, but it's not calling it in the validation. What am I doing wrong?
My input code looks like this:

<input type="text" class="form-control form-control-sm" id="inp_EMAIL" name="EMAIL" placeholder="Podem ser colocados vários endereços, separados por ponto e vírgula" required="" data-msg-required="Tem de indicar pelo menos um email" dmx-validate:custom_multiple_emails="inp_EMAIL.value.validateMultipleEmails()" data-msg-custom_multiple_emails="Um ou mais emails são inválidos. Use ';' para separar e verifique se não há emails vazios.">

How is the insert step?
Something like mail1@mail.com;mail2@mail.com?

Yes, that would be the format. The field in the database is a simple varchar field.
I wanted to validate it on the client (perhaps with a custom formatter, as Hyperbytes suggested) and on the server-side, but neither works :pensive:

Maybe you can try this:

And use

On your frontend form, you can add as many mails as you need, then a repeat on the server side: for each mail add it to the array, you can then use a set value so you can join them :slight_smile:

I'll try to make an example later if you need, little busy right now

Here's my tip for you, first try to do the formatter server-side, forget all client-side validation. Only when server-side validation is working you can start on client-side. If you can't get server-side working I doubt you'll get client-side working either (server-side is easier in my opinion)

So, let's just stick with your Set Value, make a custom formatter and show your progress here

Are you using NodeJS or PHP? I'm assuming you're using NodeJS, I'm not familiar with PHP custom formatters

Yes, server-side validation would be enough. I'm using PHP :pensive:

Shouldn't be too hard! See the docs for PHP formatters

Then you use function "explode" to split by ; and then you use a for loop and some function to validate email addresses

I managed to implement the server-side formatter and it already returns the error to the client. I just need to see how to put the error next to the input... many thanks for all the tips!

Have you considered a tagify input instead. It will do exactly what you need on the front-end and return an array to the server

This might help:

What do you want to happen if any email is invalid - throw error/message or ignore that one and continue?

if you want to stop if any are invalid, something like this might work (I have not specifically tested it!):

function formatter_checkemails($emailList){ 
    $emails = explode(',', $emailList);    
    foreach ($emails as $email) {
        $email = trim($email);
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return false;
        }
    }

    return true;
}
1 Like

I managed to solve it with the server-side formatter, but this solution of using a tagify input on the client is very well thought out! I'm going to make a version of this and then I'll see which is better. Thanks for the tip.

Mine looks like this:

function formatter_validateMultipleEmails($val) {
    if ($val === null) {
        return true; // Ou false, dependendo da sua lógica para null
    }

    $emailString = trim((string)$val);

    if ($emailString === '') {
        return true; // Campo vazio é válido por esta regra (required seria separado)
    }

    $emails = array_filter(array_map('trim', explode(';', $emailString)), function($email) {
        return $email !== '';
    });

    if (empty($emails) && $emailString !== '') {
        // Ex: o input foi só "; ; ;"
        return false;
    }
    if (empty($emails)) return true; // Se era genuinamente vazio ou só delimitadores e vazio é ok

    foreach ($emails as $email) {
        if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
            return false; // Pelo menos um email é inválido
        }
    }

    return true; // Todos os emails são válidos
}

I ended up doing the best of both worlds: on the client I used @scalaris suggestion and put in a tagify. On the server-side, I continued to use formatter validation.
Thanks to everyone for their help and tips!

1 Like