Validate Javascript fields

Asked

Viewed 810 times

2

I have several fields and others in display:none (In advance I notice that I have walked in the stack and I even found a similar question but I could not have the expected result.)

I need to validate them, but I need to enable a Ubmit button, my code is not inside a form, this is what has damaged.

My code below:

 <style>
  #btn_Codigo,
  #btn_Nome,
  #btn_Sexo{
      display: none;
  }
 </style>

        <div class="upage vertical-col left hidden" id="parte01">
        <ion-header-bar class="bar inner-element uib_w_1 bar-positive bar-header" data-uib="ionic/header" data-ver="0">
            <div class="buttons widget-container content-area horiz-area wrapping-col"></div>
            <h1 class="title">Cadastro de Tratamento</h1>
            <div class="buttons widget-container content-area horiz-area wrapping-col">
                <div class="button-bar widget uib_w_16 d-margins" data-uib="ionic/button_bar" data-ver="0"></div>
            </div>
        </ion-header-bar>
        <div style="height: 45px;"></div>

        <div class="tabs widget uib_w_18 ajusteMargin" data-uib="ionic/tab_bar" data-ver="0"><a class="tab-item widget uib_w_19" data-uib="ionic/tab_item" data-ver="0" id="btn_Pessoa">Pessoa</a><a class="tab-item widget uib_w_20" data-uib="ionic/tab_item" data-ver="0" id="btn_Consulta">Consulta</a><a class="tab-item widget uib_w_21"
            data-uib="ionic/tab_item" data-ver="0" id="btn_Pagamento">Pagamento</a>
        </div>
        <label class="item item-input item-select widget uib_w_2 d-margins" data-uib="ionic/select" data-ver="0">
            <div class="input-label">Estatus</div>
            <select id="slc_Situacao">
                <option>Ativo</option>
                <option>Inativo</option>
            </select>
        </label>
        <label class="item item-input widget uib_w_23 d-margins item-stacked-label" data-uib="ionic/input" data-ver="0"><span class="input-label">Ultimo levantamento</span>
            <input type="date" id="dt_UltimoLevantamento">
        </label>
        <label class="item item-input widget uib_w_3 d-margins borderObrigatorio" data-uib="ionic/input" data-ver="0" id="txt_Cliente">
            <i class="icon placeholder-icon ion-android-search ion"></i>
            <input type="text" placeholder="Cliente">
        </label>
        <button class="button widget uib_w_4 d-margins button-small button-balanced ion ion-android-contact icon-only" data-uib="ionic/button" data-ver="0" id="btn_NovoCliente"></button>
        <label class="item item-input widget uib_w_5 d-margins borderObrigatorio" data-uib="ionic/input" data-ver="0" id="btn_Codigo">
            <input type="text" placeholder="Código">
        </label>
        <label class="item item-input widget uib_w_6 d-margins borderObrigatorio" data-uib="ionic/input" data-ver="0" id="btn_Nome">
            <input type="text" placeholder="Nome">
        </label>
        <label class="item item-input item-select widget uib_w_7 d-margins" data-uib="ionic/select" data-ver="0" id="btn_Sexo">
            <div class="input-label">Sexo</div>
            <select id="btn_Sexo">
                <option>Masculino</option>
                <option>Feminino</option>
            </select>
        </label>
        <button class="bar button inner-element widget uib_w_8 bar-footer fixedBot  tom button-assertive ion ion-alert-circled" data-uib="ionic/button" data-ver="0" id="btn_Proximo1"></button>
    </div>

When you click the button #btn_Pessoai give a .show() in the fields to show it there it starts to be part of the requirements.

When all fields are correct I need to modify my button to the code below:

PREVIOUS:

<button class="bar button inner-element widget uib_w_8 bar-footer fixedBot  tom button-assertive ion ion-alert-circled" data-uib="ionic/button" data-ver="0" id="btn_Proximo1"></button>

POSTERIOR:

<button class="bar button inner-element widget uib_w_8 bar-footer fixedBot  tom button-balanced" data-uib="ionic/button" data-ver="0" id="btn_Proximo1">PRÓXIMO</button>

How to do all this ?

I’m doing HTML5, CSS, Jquery, I don’t have a backand, because the button just redirects to the next level of registration so to speak. Sincerely yours.

  • Can you review the question and explain what should be validated a little better? You want to validate what is inserted in the inputs and only then "go forward" and show other fields, that’s it?

  • @Sergio Actually I want the fields to be filled in, so I can go to the next step. I just need it to be filled in.

  • Okay, and can this HTML be changed? You have repeated Ids and this makes it difficult for the selectors. Each label is a field to check and only then shows the next label?

  • It can be changed yes the ID, exactly, should check each input, and only after checking the inputs of the page it can go to another.

  • Can you explain how you want to go "to another page"? You wrote that you don’t have back-end... the data is sent where? how do you want to pass data from page to page?

  • @Sergio The data will not be sent anywhere, it is a school work, where I need to make an interface just to validate, it will not really save anywhere, however I need to validate, a validation in my case, would be the fields is filled, ie I can only go to another part of the registration if it is really identified that my screen fields are all filled, (mandatory fields).

Show 1 more comment

4 answers

1

It seems that the button that will be changed by checks is the btn_Proximo1. I assume you want to validate the following elements:

<input type="text" placeholder="Cliente" id="txtCliente" required>
<input type="text" placeholder="Sexo" id="txtSexo" required>
<input type="text" placeholder="Nome" id="txtNome" required>

I would assign a class, for all of them and would handle through jQuery their respective values changes: (Assuming that class="validarElemento")

$(".validarElemento").blur(function () {
     var txtCliente = $("#txtCliente").val();
     var txtSexo = $("#txtSexo").val();
     var txtNome = $("#txtNome").val();           

     //condições
     if (txtCliente != "" && txtSexo != "") {
         //Alterar propriedades do botão:
         $("#btn_Proximo1").toggleClass('bar button inner-element widget uib_w_8 bar-footer fixedBot  tom button-balanced');
         $("#btn_Proximo1").val("");
     }        
});

1


You can use an angular directive to validate as below:
(check explanatory comments in Javascript)

angular.module('myApp', ['ionic']).directive('onValidSubmit', ['$parse', '$timeout',
function($parse, $timeout) {
    return {
        /* Define requisito diretiva, ou seja, só irá rodar dentro da tag form */
        require: '^form',
        restrict: 'A',
        /* Compila diretiva */
        link: function(scope, element, attrs, form) {
            form.$submitted = false;
            var fn = $parse(attrs.onValidSubmit);
            /* Atribui evento onsubmit no form relacionado a diretiva */
            element.on('submit', function(event) {
                scope.$apply(function() {
                    element.addClass('ng-submitted');
                    form.$submitted = true;
                    /* Verificar o estado dos campos que estão presente no form, ou seja, se estão validos de acordo com a validação denifida. Essa obdece o padrão do HTML5 com a tag required */
                    if (form.$valid) {
                        if (typeof fn === 'function') {
                            fn(scope, {
                                /* Chama funcão callback caso a validação esteja OK */
                                $event: event
                            });
                        }
                    }
                });
            });
        }
    };
}]).controller('AppController', function($scope){
    /* Funcao callback executada caso a validação retorne um OK */
    $scope.aposValidarDadosOK = function(){
        console.log("Proximo.......");
    };
});
#btn_Codigo,
  #btn_Nome,
  #btn_Sexo {
    display: none;
  }
  input.ng-dirty.ng-invalid {
    border: 1px solid red;
  }
  form i.icon.error {
    color: #ef4e3a;
  }
  form input + i.icon.error {
    display: none;
    margin-left: 8px;
  }
  form select + i.icon.error {
    display: none;
    margin-left: 8px;
  }
  form.ng-submitted input.ng-invalid + i.icon.error {
    display: block;
  }
  form.ng-submitted select.ng-invalid + i.icon.error {
    display: block;
  }
  form .has-error {
    border-left: 3px solid #cc2511;
    border-right: 3px solid #cc2511;
  }
  form .has-success {
    border-left: 3px solid #3d8b3d;
    border-right: 3px solid #3d8b3d;
  }
  form.ng-submitted input.ng-valid + i.icon.error {
    display: none;
  }
  form.ng-submitted select.ng-valid + i.icon.error {
    display: none;
  }
  .validated {
    display: -webkit-box;
    display: -webkit-flex;
    display: -moz-box;
    display: -moz-flex;
    display: -ms-flexbox;
    display: flex;
    padding: 0px;
    width: 100%;
  }
  .validated .input-label {
    -webkit-box-flex: 0;
    -webkit-flex: 0 0 30%;
    -moz-box-flex: 0;
    -moz-flex: 0 0 30%;
    -ms-flex: 0 0 30%;
    flex: 0 0 30%;
    max-width: 30%;
  }
  .validated input {
    -webkit-box-flex: 0;
    -webkit-flex: 0 0 60%;
    -moz-box-flex: 0;
    -moz-flex: 0 0 60%;
    -ms-flex: 0 0 60%;
    flex: 0 0 60%;
    max-width: 60%;
  }
  .validated error {
    -webkit-box-flex: 0;
    -webkit-flex: 0 0 10%;
    -moz-box-flex: 0;
    -moz-flex: 0 0 10%;
    -ms-flex: 0 0 10%;
    flex: 0 0 10%;
    max-width: 10%;
  }
  .item-stacked-label i.icon.error {
    position: absolute;
    top: 10px;
    right: 10px;
  }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link rel="stylesheet" href="http://code.ionicframework.com/1.1.0/css/ionic.css">
<script src="http://code.ionicframework.com/1.1.0/js/ionic.min.js"></script>
<script src="http://code.ionicframework.com/1.1.0/js/ionic-angular.js"></script>
<script src="http://code.ionicframework.com/1.1.0/js/ionic.bundle.js"></script>

<div class="upage vertical-col left hidden" ng-app="myApp" ng-controller="AppController">
    <ion-header-bar class="bar inner-element uib_w_1 bar-positive bar-header" data-uib="ionic/header" data-ver="0">
        <div class="buttons widget-container content-area horiz-area wrapping-col"></div>
        <h1 class="title">Cadastro de Tratamento</h1>
        <div class="buttons widget-container content-area horiz-area wrapping-col">
            <div class="button-bar widget uib_w_16 d-margins" data-uib="ionic/button_bar" data-ver="0"></div>
        </div>
    </ion-header-bar>
    <br>
    <br>
    <div style="margin:10px;">
        <form  novalidate="novalidate" on-valid-submit="aposValidarDadosOK()">
            <label class="item item-input item-select widget uib_w_2 d-margins" data-uib="ionic/select" data-ver="0">
                <div class="input-label">Status</div>
                <select id="slc_Situacao" required ng-model="status">
                    <option></option>
                    <option>Ativo</option>
                    <option>Inativo</option>
                </select>
                <i class="icon ion-alert-circled error">*</i>
            </label>
            <br>
            <br>
            <label class="item item-input widget uib_w_3 d-margins borderObrigatorio" data-uib="ionic/input" data-ver="0" id="txt_Cliente">
                <i class="icon placeholder-icon ion-android-search ion"></i>
                <input type="text" placeholder="Cliente" ng-model="cliente" required>
                <i class="icon ion-alert-circled error col col-10">*</i>
            </label>
            <br>
            <br>
            <div>
                <button type="submit" class="button icon-right ion-chevron-right button-block button-energized active">
                    Próximo
                </button>
            </div>
        </form>
    </div>
</div>

NOTE: To view the example, open in mode Whole page. For some reason you’re cutting the next button.

  • Could you comment on the code ? Because it is useless to put it to work but do not understand the process.

  • Do you know angular? Know about directives? What is your level of frontend knowledge?

  • Angular understand qse nothing, directive nothing, and frontend the advanced but became obsolete..

  • 4

    The evening I put a detail explaining each function pq now I am working. More already advance that without knowing of angular vc will get confused enough. Incidentally I saw that you are using the Ionic that runs with angled low cloths. If you want to explore all the facilities of the framework I strongly recommend that you do a study on angular. And any doubt can post here in the community.

  • OK I await your comment

  • There’s the comment from the source

  • @Renanrodrigues was clear my comment?

  • Emir thought the teaching was nice, and I saw that it worked, but due to lack of knowledge of the angular js I will choose another answer that was the one I used in my project. But you are to be congratulated, thank you, and I will study more on the subject.

  • 2

    Okay, just a comment I’d like to make. The use of another js library other than angular in my view kills quite a lot of the usability of the Ionic framework. Even though you have found another answer that helped you this should certainly use jquery or something like that. So it is a "less correct" answer for not using something that is already embedded in Ionic. Rethink well which answer is smarter. Not always the answer you used may be ideal for the topic ;)

  • 2

    And finally take a look here: http://www.infoq.com/br/presentations/vale-a-pena-usar-cordova-phonegap, very good talk in Portuguese that speaks precisely about Cordova +Ionic +angular. This guy even talks about performance and etc... He also speaks the pq is ideal to use the angular with Ionic (avoid access to DOM) . Hugs!

Show 5 more comments

1

You can put a class in all input and in jquery check if it is empty, leave the button disabled, if you pass the validation you enable the button.

$('.campo').each(function() {
  if ($(this).val() != 0 && $(this).val() != '') {
    $("id_botao").removeAttr("disabled");
  }
});

-3

What backend are you using? If it’s PHP, you can do the following:

if (isset('submit'){    //substitua o submit pelo nome do primeiro botão que a pessoa precisa clicar para habilitar os outros campos

            $mostrarCampos= "display:none";
        }
        else {
            $mostraCampos = "";
        }
}

This will work even if you are not inside the form, but I would recommend putting everything inside the form, since you will want to save this information (the information that was inserted before clicking the button and the information that will be inserted next) in a bank.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.