Mariana
Mariana

Reputation: 170

Validating fields before submit

I have this function that validates some form fields:

$('#FornecedorNovo').submit(function (e) {
e.preventDefault();
var url = "/Fornecedor/VerificaInscricao";
var Insc = $("#InscricaoEstadual").val();
var Isento = $("#InscricaoIsento").prop('checked');
var form = this,
    $form = $(form); // Salvamos o formulário atual em uma variável

    $.ajax({
        url: url,
        data: { insc: Insc, isento: Isento },
        datatype: "json",
        type: "POST",
        success: function (data) {
            if (data.resultado == true) {
                $("#messageI").html(data.mensagem);
                if (data.mensagem != 'O campo Inscrição é obrigatório.') {
                    $("#InscricaoEstadual").val('');
                    $("#InscricaoEstadual").focus();
                }
            } else {
                var url1 = "/Fornecedor/VerificaDocumento";
                var Documento = $("#Documento").val();

                $.ajax({
                    url: url1,
                    data: { documento: Documento },
                    datatype: "json",
                    type: "POST",
                    success: function (data) {
                        if (data.resultado == true) {
                            $("#message").html(data.mensagem);
                            $("#Documento").val('');
                            $("#Documento").focus();
                        }
                        else {
                            $form.off('submit').submit();
                        }
                    }
                });
            }
        }
    })
});

But it happens that I have the validation already for dataannotations, and that's what I'm doing, if it falls into $ form.off ('submit'). Submit ();, it sends the form, without validating the fields, causing errors as they are required fields. Is there a way this does not occur? I use ASP.NET CORE.

Upvotes: 0

Views: 31

Answers (1)

akaBase
akaBase

Reputation: 2250

Im not understanding why your using Ajax to make sure items aren't null?

you can check for them with

var error = false;
if(!$('#InscricaoIsento').is(':checked')){
    error = true;
    NotCheckedResponse();
}
if($("#InscricaoEstadual").val() == "" || $("#InscricaoEstadual").val() == null){
    error = true;
    NotFilledResponse();
}
if(!error){
    SubmitForm();
}

Unless I misunderstood something surely doing the checks like this would make it a lot simpler for you.

Upvotes: 1

Related Questions