Nesse conteúdo quero mostrar a você como validar formulários criados com o Elementor PRO através do backend usando Ajax (hooks/API).
Torne-se Especialista em Elementor…
Faça o Curso Mais Completo e Acessível do Brasil!
MATRICULE-SE AGORA
Veja o vídeo:
[embedyt]https://www.youtube.com/watch?v=VDadtQaAatI[/embedyt]
O Elementor Pro é uma excelente opção se você deseja ter uma suíte quase completa para criar sites, contendo funcionalidades úteis e produtivas.
Obtenha o Elementor PRO – vale muito a pena.
Como você deve saber, o Elementor trabalha com widgets, e um dos mais importantes é o de formulários ou também chamado de Elementor Forms.
Como um WordPress Form Builder (construtor de formulários), o Elementor Forms nos permite criar formulários bastante funcionais para diferentes necessidades, rapidamente.
Além disso, tem as “Ações após enviar” (ações após pressionar o botão enviar) que são bastante úteis, e o melhor de tudo, que podem ser combinadas.
Desse modo, por exemplo, você poderia ter essa combinação:
- Adicionar uma pessoa a uma mailing list
- Enviar uma mensagem para o administrador e outra para quem enviou o formulário
- Enviar um webhook para o Zapier ou outro serviço similar
- Ao final, redirecionar o usuário para uma página de agradecimento.
Portanto, Formulários do Elementor são excelentes e não perdem muito para o plugins específicos e mais robustos de formulários, como Gravity Forms.
No entanto, há um problema se você quiser ter um formulário mais sério, porque não há validações realmente úteis, nativamente, no Elementor.
Como assim? O Elementor possui apenas validação básica de frontend usando correspondências e obrigatoriedade nos campos.
Contudo, alguém usando o Inspetor (Element Inspector) de qualquer navegador pode modificar o código e enviar qualquer informação sem ser validada de acordo.
Por exemplo, você pode abrir o Inspetor de Elementor e trocar o tipo de campo do e-mail para tentar enviar sem validar esse e-mail.
Agora, algumas pessoas optam por usar bibliotecas Javascript ou jQuery puras para validar os formulários, e isso parece até uma coisa interessante.
Entretanto, isso traz outro problema que é adicionar um peso adicional ao que já possui o Elementor e suas bibliotecas, comprometendo a performance.
Além disso, se o usuário sabe desativar o Javascript, todas essas validações vão pelo ralo.
Como validar campos de formulários?
Sim, há uma solução para fazer as validações – por backend.
Desta forma, mesmo que o usuário utilize o inspetor ou desabilite o javascript, os dados ainda serão validados.
A boa notícia, é que o Elementor Forms possui Hooks que permitem validação de backend (server-side) que podem retornar mensagens de erro em tempo real via Ajax.
Veja a documentação em Elementor Forms API.
Para fazer isso, você deve criar um plugin ou editar o arquivo functions.php do seu tema (recomendo trabalhar com um tema filho) para adicionar essas validações.
Aqui está um exemplo para uma validação global:
// Validate the Ticket ID field is in XXX-XXXX format.
add_action( 'elementor_pro/forms/validation', function ( $record, $ajax_handler ) {
$fields = $record->get_field( [
'id' => 'ticket_id',
] );
if ( empty( $fields ) ) {
return;
}
$field = current( $fields );
if ( 1 !== preg_match( '/^\w{3}-\w{4}$/', $field['value'] ) ) {
$ajax_handler->add_error( $field['id'], 'Invalid Ticket ID, it must be in the format XXX-XXXX' );
}
}, 10, 2 );
Usando o Hook elementor_pro/forms/validation
você pode fazer a validação em todas as submissões de formulários do Elementor.
Os argumentos que vemos acima para a função são os seguintes:
Argumento | Modelo | Descrição |
---|---|---|
record | Form_Record | O registro enviado. |
ajax_handler | Ajax_Handler | O componente Manipulador Ajax. |
Você também pode fazer validações por tipo de campo, usando o Hook elementor_pro/forms/validation/{$field_type}
.
Isso vai permitir validar tipos de campo individuais, como por exemplo os campos de telefone, email, etc.
Aqui está um exemplo:
// Validate the Tel field is in XXX-XXX-XXXX format.
add_action( 'elementor_pro/forms/validation/tel', function( $field, $record, $ajax_handler ) {
// Match this format XXX-XXX-XXXX, 123-456-7890
if ( preg_match( '/[0-9]{3}-[0-9]{3}-[0-9]{4}/', $field['value'] ) !== 1 ) {
$ajax_handler->add_error( $field['id'], 'Please make sure the phone number is in XXX-XXX-XXXX format, eg: 123-456-7890' );
}
}, 10, 3 );
Os argumentos que vemos acima são os seguintes:
Argumento | Modelo | Descrição |
---|---|---|
field | Array | O campo enviado. |
record | Form_Record | O registro enviado. |
ajax_handler | Ajax_Handler | O componente Manipulador Ajax. |
Esses são recursos bem úteis que vão facilitar bastante a validação de formulários do Elementor do lado do servidor (backend).
Validação de E-mails
Agora, por exemplo, a validação de e-mails no Elementor, quando você usa o tipo de campo e-mail, verifica se há um arroba (@) e um ponto (.), o que não é tão preciso.
Assim, poderíamos criar uma função de validação da seguinte forma:
add_action( 'elementor_pro/forms/validation/email', function( $field, $record, $ajax_handler ) {
if ( !filter_var( $field['value'], FILTER_VALIDATE_EMAIL ) ) {
$ajax_handler->add_error( $field['id'], 'Insira um e-mail válido.' );
}
}, 10, 3 );
Então, você pode ter mais precisão usando a função filter_var()
do PHP ou mesmo a função is_email() do WordPress para ser mais eficaz.
Validação por ID de campo
Cada campo no Elementor Forms tem um ID que podemos personalizar – isso é um recurso muito útil e uma prática recomendada.
Graças a isso, podemos fazer uma validação geral em todos os formulários do nosso site onde os campos tenham o mesmo ID, o que vai facilitar bastante.
Então, vamos criar uma função extra que nos permita obter um campo pelo ID inserido, da seguinte forma:
function elementor_get_field($id, $record){
$fields = $record->get_field([
'id' => $id
]);
if(empty($fields)){
return false;
}
return current($fields);
}
E aqui está a função de exemplo que usei no vídeo que mostrar como usar a função acima e executar validações em diversos campos:
function valida_campos( $record, $ajax_handler ) {
if($field = elementor_get_field('aceita_termos', $record)){
if($field['value']!= 'on'){
$ajax_handler->add_error( $field['id'], 'Você precisa aceitar os termos!' );
}
}
if($field = elementor_get_field('idade', $record)){
if(empty( trim($field['value']))){
$ajax_handler->add_error( $field['id'], 'Insira sua idade' );
}else if(!filter_var(trim($field['value']), FILTER_VALIDATE_INT )){
$ajax_handler->add_error( $field['id'], 'Somente números...' );
}
//
}
if($field = elementor_get_field('nome', $record)){
if(empty( trim($field['value']))){
$ajax_handler->add_error( $field['id'], 'Insira seu nome' );
}else if(3 >= strlen(trim($field['value']) )){
$ajax_handler->add_error( $field['id'], 'Pelo menos 3 caracteres...' );
}
}
}
O último passo é acionar essa função no Hook de validação de formulários do Elementor usando add_action
:
add_action('elementor_pro/forms/validation','valida_campos', 10, 2);
É isso! Acho que com esse base você será capaz de realizar qualquer tipo de validação em formulários do Elementor.
Se você precisar, pode pesquisar no Google sobre funções para validação de campos específicos como CPF, telefones brasileiros, etc.
Eu criei um arquivo com diversas validações no GitHub Gist (veja aqui).
Você gostou desse conteúdo? Deixe um comentário abaixo:
54 respostas
Great information shared.. really enjoyed reading this post thank you author for sharing this post .. appreciated
deneme bonusu veren siteler
child porn
I loved as much as you will receive carried out right here. The sketch is attractive, your authored material stylish. nonetheless, you command get got an impatience over that you wish be delivering the following. unwell unquestionably come more formerly again since exactly the same nearly a lot often inside case you shield this hike.
I’ve read several just right stuff here. Certainly price bookmarking for revisiting. I wonder how a lot effort you place to create this kind of great informative website.
I do believe all the ideas you’ve presented for your post. They are really convincing and will certainly work. Nonetheless, the posts are too short for novices. May just you please lengthen them a little from subsequent time? Thanks for the post.
Hello Neat post Theres an issue together with your site in internet explorer would check this IE still is the marketplace chief and a large element of other folks will leave out your magnificent writing due to this problem
Hello my loved one I want to say that this post is amazing great written and include almost all significant infos I would like to look extra posts like this
hello!,I really like your writing so a lot! share we keep up a correspondence extra approximately your post on AOL? I need an expert in this house to unravel my problem. May be that is you! Taking a look ahead to see you.
hi!,I like your writing so much! share we be in contact more approximately your article on AOL? I need a specialist in this area to resolve my problem. Maybe that is you! Looking ahead to see you.
you are truly a just right webmaster. The site loading speed is incredible. It kind of feels that you’re doing any distinctive trick. In addition, The contents are masterwork. you have done a great activity in this matter!
Thank you for the auspicious writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! However, how can we communicate?
Hey there, You have done a fantastic job. I will certainly digg it and personally recommend to my friends. I’m confident they’ll be benefited from this site.
you are truly a just right webmaster. The site loading speed is incredible. It kind of feels that you’re doing any distinctive trick. In addition, The contents are masterwork. you have done a great activity in this matter!
I liked it as much as you did. Even though the picture and writing are good, you’re looking forward to what comes next. If you defend this walk, it will be pretty much the same every time.
Thanks I’ve been searching for info on this topic for a while and yours is the best I’ve found. However, what about the bottom line? Are you sure about the supply?
My brother suggested I might like this blog He was totally right This post actually made my day You can not imagine simply how much time I had spent for this info Thanks
Thanks for finally writing about > Como Validar Formulários
do Elementor (PRO) ➜ Aula Completa (2022) • WP24HORAS < Loved it!
tipobet
It was great seeing how much work you put into it. The picture is nice, and your writing style is stylish, but you seem to be worrying that you should be presenting the next article. I’ll almost certainly be back to read more of your work if you take care of this hike.
Hi Neat post There is a problem along with your website in internet explorer would test this IE still is the market chief and a good section of other folks will pass over your magnificent writing due to this problem
child porn sex
can i buy viagra over the counter
Thanks I have just been looking for information about this subject for a long time and yours is the best Ive discovered till now However what in regards to the bottom line Are you certain in regards to the supply
Excellent blog here Also your website loads up very fast What web host are you using Can I get your affiliate link to your host I wish my web site loaded up as quickly as yours lol
I do not even know how I ended up here but I thought this post was great I do not know who you are but certainly youre going to a famous blogger if you are not already Cheers
Magnificent beat I would like to apprentice while you amend your site how can i subscribe for a blog web site The account helped me a acceptable deal I had been a little bit acquainted of this your broadcast offered bright clear idea
My brother recommended I might like this web site He was totally right This post actually made my day You cannt imagine just how much time I had spent for this information Thanks
yeteneksiz
http://www.tvoidom.galaxyhost.org/forums.php?m=posts&q=31142&n=last#bottom
https://samizdat.org/index.php/Mp3bit.pw_3
http://slavuta.0pk.me/viewtopic.php?id=3282#p10467
https://xdpascal.com/index.php/User:IleneMallette66
Insightful piece
Para Que Sirve Cialis 20 Mg Precio
You have hit the mark. It is excellent thought. I support you.
Cialis 5 mg prezzo prezzo cialis 5 mg originale in farmacia cialis 5 mg prezzo
citalopram to escitalopram
what is gabapentin used for dogs
Wow, marvelous weblog format! How long have you ever been blogging for?
you make running a blog look easy. The full glance of your website is great, as neatly
as the content! You can see similar here najlepszy sklep
ddavp and thrombocytopenia
what does citalopram do
For the reason that the admin of this website is working, no uncertainty very shortly it will be famous, due to its quality contents.
cs:go skin gambling sites https://voicify.com/wp-content/pgs/?steam-cs-go-gambling-a-dive-into-the-virtual-betting-arena.html cs go gambling site
losartan cozaar 50 mg
generic depakote
Hello, its pleasant article regarding media print, we all be aware of media is a fantastic source of data.
http://www.google.com.sb/url?q=https://hottelecom.biz/id/
My brother recommended I might like this web site. He was totally
right. This post truly made my day. You can not imagine simply
how much time I had spent for this information! Thanks!
I saw similar here: Sklep internetowy
Wow superb blog layout How long have you been blogging for you make blogging look easy The overall look of your site is magnificent as well as the content
losartan cozaar recall
ddavp iv diabetes insipidus
how does citalopram make you feel at first
depakote withdrawal symptoms
Thanks for the help in this question, the easier, the better …
Подробно расскажем, как Взыскать долг по договору займа – Ленинский районный суд г. Иркутска онлайн или самостоятельно Взыскать долг по договору займа – Ленинский районный суд г. Иркутска Взыскать долг по договору займа – Ленинский районный суд г. Иркутска онлайн или самостоятельно
Comprar Cialis Online Seguro
These are all fairy tales!
Cialis 5 mg prezzo prezzo cialis 5 mg originale in farmacia tadalafil 5 mg prezzo
Yes, happens…
koop voor altijd een virtueel telefoonnummer
Aviator Spribe казино как играть
Добро пожаловать в захватывающий мир авиаторов! Aviator – это увлекательная игра, которая позволит вам окунуться в атмосферу боевых действий на небе. Необычные графика и захватывающий сюжет сделают ваше путешествие по воздуху неповторимым.
Авиатор Спрайб играть онлайн