Home > Software design >  Validate the form before sending the data via AJAX to resources. Liferay 7.3.5
Validate the form before sending the data via AJAX to resources. Liferay 7.3.5

Time:12-02

I am developing a form in Liferay 7.3.5. The purpose of the form is to validate the data before sending it AJAX to resources.

The code is working fine, the problem I have is that I cannot find the solution to validate the form fields before sending the data by AJAX. The AJAX code snippet is as follows

//Evento boton de formulario
        $('#<portlet:namespace/>button-contactForm').click(function(){
                
            var form = $('#<portlet:namespace/>fm')[0];
            var data = new FormData(form);
        
            $.ajax({
                type: "POST",
                //enctype: 'multipart/form-data',
                url: '${emailResourceURL}',
                data: data,
                processData: false,
                contentType: false,
                cache: false,
                timeout: 600000
                  
            }).done(function( data, textStatus, jqXHR ) {
                $('#<portlet:namespace/>fm').trigger('reset');
                console.log("La solicitud se ha completado correctamente." );
                
            }).fail(function( jqXHR, textStatus, errorThrown ) {
                console.log("La solicitud ha fallado: "    textStatus);
                
            });
            
        }); 

How can I validate the form fields in this case? I showed you the complete code, below.

<%@ include file="/init.jsp" %>

<portlet:resourceURL id="email" var="emailResourceURL"/>
<portlet:resourceURL id="captcha" var="captchaResourceURL"/>

<div id="contactForm">
    <div class="content-width-section">
        <aui:form name="fm" method="post" enctype="multipart/form-data">
            <aui:fieldset-group markupView="lexicon">
            
                <aui:fieldset label="form.field.title">
                    <aui:input id="subject-contactForm" placeholder="form.field.subject" label="" name="${subject}" type="text">
                        <aui:validator name="required"></aui:validator>
                    </aui:input>
                    
                    <aui:row>
                        <aui:col width="50">
                            <aui:input id="name-contactForm" placeholder="form.field.name" label="" name="${name}" type="text">
                                <aui:validator name="required"></aui:validator>
                            </aui:input>
                        </aui:col>
                        
                        <aui:col width="50">
                            <aui:input id="surname-contactForm" placeholder="form.field.surname" label="" name="${surname}" type="text">
                                <aui:validator name="required"></aui:validator>
                            </aui:input>
                        </aui:col>
                    </aui:row>
                    
                    <aui:row>
                        <aui:col width="50">
                            <aui:input id="email-contactForm" placeholder="form.field.email" label="" name="${email}" type="text">
                                <aui:validator name="required"></aui:validator>
                                <aui:validator name="email"></aui:validator>
                            </aui:input>
                        </aui:col>
                        
                        <aui:col width="50">
                            <aui:input id="phone-contactForm" placeholder="form.field.phone" label="" name="${phone}" type="text">
                                <aui:validator name="digits"></aui:validator>
                            </aui:input>
                        </aui:col>
                    </aui:row>
                    
                    <aui:input id="message-contactForm" placeholder="form.field.message" label="" name="${message}" type="textarea">
                        <aui:validator name="required"></aui:validator>
                    </aui:input>

                    <div class="input-group">
                        <div class="input-file-upload col-xs-12 col-sm-8 col-md-9 col-lg-10">
                            <aui:input id="fileName-contactForm" placeholder="form.field.attached.document" label="" name="${fileName}" type="text" />
                        </div>
                        <div class="btn-file-upload col-xs-12 col-sm-4 col-md-3 col-lg-2">
                            <aui:input id="attachedDocument-contactForm" label="form.button.attached.document" name="${attachedDocument}" type="file" >
                                <aui:validator name="acceptFiles">'doc,docx,pdf'</aui:validator>
                            </aui:input>
                        </div>
                    </div>
                    
                    <aui:input name="form.field.privacy.policy" type="radio">
                        <aui:validator name="required"></aui:validator>
                    </aui:input>
                    
                    <liferay-captcha:captcha url="${captchaResourceURL}" />     
                </aui:fieldset>
                
            </aui:fieldset-group>
            
            <aui:button-row>
                <aui:button id="button-contactForm" name="button" type="button" value="form.button.send" />
            </aui:button-row>
        </aui:form>
    </div>
</div>

<script>

    //Bordes y titulo del formulario
    $('#contactForm .main-content-card').removeClass('card-horizontal');
    $('#contactForm #Title').addClass('h2 title-section text-center my-4');
    
    //Boton seleccion de documento adjunto
//  $('#contactForm .input-group .input-file-upload input').attr('disabled', '');   
    $('#contactForm .input-group .btn-file-upload label').addClass('buttonBlue mayusculas p-2 d-flex justify-content-center');
    
    //Radio button 'politica de privacidad'
    $('#contactForm .radio').addClass('textGraySade');
    $('#contactForm .radio.textGraySade label').addClass('d-flex align-items-center');
    
    //Boton de envio de formulario
    $('#contactForm button').removeClass('btn-primary btn-secondary').addClass('buttonBlue mayusculas');
    $('#contactForm .button-holder').addClass('d-flex justify-content-center');
    
    $(document).ready(function(){
        
        //Evento boton seleccion de documento adjunto
        $('#contactForm .btn-file-upload input:file').change(function(){
            var pathFile = $(this).val();
            var indexToken = pathFile.lastIndexOf('\\')   1;
            var fileName = pathFile.substring(indexToken, pathFile.length);
            
            $('#contactForm .input-file-upload input:text').val("");
            $('#contactForm .input-file-upload input:text').val(fileName);
        });
        
        //Evento campo de texto de documento adjunto
        $('#contactForm .input-file-upload input:text').click(function(){
            $(this).val('');
            $('#contactForm .btn-file-upload input:file').val('');
        });
        
        //Evento boton de formulario
        $('#<portlet:namespace/>button-contactForm').click(function(){
                
            var form = $('#<portlet:namespace/>fm')[0];
            var data = new FormData(form);
        
            $.ajax({
                type: "POST",
                enctype: 'multipart/form-data',
                url: '${emailResourceURL}',
                data: data,
                processData: false,
                contentType: false,
                cache: false,
                timeout: 600000
                  
            }).done(function( data, textStatus, jqXHR ) {
                $('#<portlet:namespace/>fm').trigger('reset');
                console.log("La solicitud se ha completado correctamente.");
                
            }).fail(function( jqXHR, textStatus, errorThrown ) {
                console.log("La solicitud ha fallado: "    textStatus);
                
            });
            
        }); 
        
    });

</script>

Thanks!

Regards!

CodePudding user response:

You can validate the form with js before the ajax call. Modify your ajax code snippet to this

        //Evento boton de formulario
        $('#<portlet:namespace/>button-contactForm').click(function(){
            
            // get your form validator
            var formValidator = Liferay.Form.get('<portlet:namespace />fm').formValidator;

            // manually validates the form
            formValidator.validate();
            
            // verify if there are errors. If so, returns nothing
            if (formValidator.hasErrors()) return;
            
            var form = $('#<portlet:namespace/>fm')[0];
            var data = new FormData(form);
        
            $.ajax({
                type: "POST",
                enctype: 'multipart/form-data',
                url: '${emailResourceURL}',
                data: data,
                processData: false,
                contentType: false,
                cache: false,
                timeout: 600000
                  
            }).done(function( data, textStatus, jqXHR ) {
                $('#<portlet:namespace/>fm').trigger('reset');
                console.log("La solicitud se ha completado correctamente.");
                
            }).fail(function( jqXHR, textStatus, errorThrown ) {
                console.log("La solicitud ha fallado: "    textStatus);
                
            });
            
        }); 

  • Related