Enable/Disable button according to field validation

Asked

Viewed 10,294 times

4

I am performing date validation for two fields <input type="text"> with the jQueryFormValidator:

        $.validate({
            modules : 'date'
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.1.47/jquery.form-validator.min.js"></script>

<form>

<input type="text" class="form-control" name="Tdesl"  maxlength="10" data-validation="date" data-validation-format="dd/mm/yyyy" placeholder="dd/mm/aaaa" OnKeyPress="formatar('##/##/####', this)" id="Cdesl22"></label>

    <input class="form-control" type="text" data-validation="date" data-validation-format="dd/mm/yyyy" maxlength="10" placeholder="dd/mm/aaaa" OnKeyPress="formatar('##/##/####', this)" name="Tinsem3" id="Cinsem"></label>

</form>

But I cannot make that, when these fields are validated, that a button (<button="button"> is not a submit) is enabled.

According to some answers I saw in Soen, the jQueryFormValidator not native support for this function, so I’m trying to adapt that script (the link is FIDDLE, but I found it by Soen):

    $('#myform > input').on('input', function () {
        var empty = false;
        $('form > input, form > select').each(function () {
            if ($(this).val() == '') {
                empty = true;
            }
        });
    
        if (empty) {
            $('#register').attr('disabled', 'disabled');
        } else {
            $('#register').removeAttr('disabled');
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform">Username
    <br />
    <input type="text" class="class" id="user_input" name="username" />
    <br />Password
    <br />
    <input type="password" id="pass_input" name="password" />
    <br />Confirm Password
    <br />
    <input type="password" id="v_pass_input" name="v_password" />
    <br />Email
    <br />
    <input type="text" id="email" name="email" />
    <br />Birthday
    <br />
    <input type="date" id="bday" name="birthday" />
    <br />Sex
    <br />
    <select name="sex" id="sex">
        <option>Male</option>
        <option>female</option>
    </select>
    <input type="submit" id="register" value="Register" disabled="disabled" />
</form>

However, this script requires all fields input are completed, and I need only two (there are more fields on the form, and I need only two of them to be observed). I tried to create a class to apply in these two fields, but I guess I didn’t do it right:

$('#myform > .classinput').on('input', function () {

Also, this script uses the type date, while in my case I’m using type fields text, but that are being validated for date, so if it were possible to use the validation result (to enable the button) would be ideal, but otherwise it can only be with the basic rules, like accept for the day at the most 31, in the month 12, in the year 2015, etc.

2 answers

2

I made a change with the class obrig for the validated fields:

$('#myform > input').on('input', function () {
    var empty = false;
    $('form > .obrig').each(function () {
        if ($(this).val() == '' ) {
            empty = true;
        }else {
            empty = false;
        }
    });
     if (empty) {
        $('#register').attr('disabled', 'disabled');
    } else {
        $('#register').removeAttr('disabled');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform">Username
    <br />
    <input type="text" class="obrig" id="user_input" name="username" />
    <br />Password
    <br />
    <input type="password" class="obrig"  id="pass_input" name="password" />
    <br />Confirm Password
    <br />
    <input type="password" id="v_pass_input" name="v_password" />
    <br />Email
    <br />
    <input type="text" id="email" name="email" />
    <br />Birthday
    <br />
    <input type="date" class='obrig' id="bday" name="birthday" />
    <br />Sex
    <br />
    <select name="sex" id="sex">
        <option>Male</option>
        <option>female</option>
    </select>
    <input type="submit" id="register" value="Register" disabled="disabled" />
</form>

  • Cool +1, now only need to validate the field as date before enabling the button.

  • puts the class='forcing' that solves

  • So, but the field is text, and it has to be validated to date before opening the button. In this case it will only require you to have any fill-in, as if it were a text field, and I need it either to take the validation that you use (form-Validator), or to do another one, but any way it validates that it is a correct date before enabling the button...

1


Let’s see

Of jQuery I understand almost nothing - I prefer my code in Javascript pure (without frameworks). I finally learned a little bit about jQuery trying to solve your problem. And in the end, I think it was solved..


Explanation

Here is a brief explanation of the code and the process. It may facilitate understanding.

In the JS

  • I added the $.validate(); because I needed to verify that the date check worked correctly with the code, obviously;
  • In $.validate();, added the return(false) to prevent the sending of the form in the event of further checks of other elements of the form;
  • Within the scope of $('form > .checarData'), I believe the .on('validation', ... so that there was a way to determine the activation of the button;

In HTML

  • the ID element #aniv2 serves as mirror of the ID element #aniv1. That is, whatever you have in #aniv1 will have in #aniv2.

In this case, the more dates to be validated you have had, each of them will have to have a mirror element. Why?

Behold: the jQuery Form Validator needs that the attribute type be equal to text as you said yourself. BUT, after the form is submitted, you will need it to be of the type date.

Thus, having both elements, being a mirror of the other, you can validate the date and still get the form with the 'birthday' field of type date to format on the destination page, whatever. And as one of them is hidden, the user will not see this mirror element.


& Example Code

$.validate({
    modules: 'date',
    onSuccess: function () {

        /* Impede o envio do formulário */
        return (false);

    }
});

/* 'form' é a TAG mesmo */
$('form > .checarData').on('validation', function (evt, valid) {

    /* Copia #aniv1 em #aniv2 */
    document.getElementById("aniv2").value = document.getElementById("aniv1").value;
    
    /* Verifica se o campo não está vazio E SE a data está OK */
    if (valid) {
        $('#registrar').removeAttr('disabled');
    } else {
        $('#registrar').attr('disabled', 'disabled');
    }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.1.47/jquery.form-validator.min.js"></script>

<form id="formulario">

  Usuário
  <br />
  <input type="text" id="user" name="username" />

  <br />Email
  <br />
  <input type="text" id="email" name="email" />

  <br />Aniversário
  <br />
  <input type="text" id="aniv1" name="aniv1" class="checarData" data-validation="birthdate" data-validation-format="dd/mm/yyyy" />

  <!-- Espelho de #aniv1, porém do tipo "date" -->
  <input type="date" id="aniv2" name="aniv2" hidden="hidden" />

  <br />

  <input type="button" id="registrar" value="Registrar" disabled="disabled" />

</form>


Notes

You must understand of jQuery enough to know how to insert the .on('input', ... in place of .on('blur', .... I’m really not the master on this framework and have never used it directly professionally - only when it appears in third party libraries on systems not developed by me.

Ah! Just in case, Jsfiddle to ensure!

I hope I’ve helped!

  • Man, it’s sure going to help a lot! + 1 Just the explanations you’ve given have helped me understand a lot here... I’m studying the code and trying to implement, but I have no deep knowledge in jQuery no (I’m quite beginner incidentally)... I’m passing the results here... Thank you very much!

  • Then, it validates the date in the text field, but does not enable the button. Even in Jsfiddle, or in the example above, the enabling is not working. I’m doing some tests here, but I don’t need you to check if the field is empty, if it is with the right date, don’t need to check if it is empty (none, just the same date). I do not understand very well why the input fields with Hidden... inspecting through the browser can see the tag form modifying error for has-sucess, when validates... can not use this as parameter to enable the button, that is, if it is has-sucess enables?

  • What I said about seeing the tag form changing to has Success is in Chrome, in Elements.

  • Thanks Jose, I adapted here and it worked, I posted an answer to show what I did, take a look to see if there is something that can improve... Hugs.

  • I took a look at what you said. The blank field check is present because it was in the original code of the question. But if you don’t need to, just remove the class checar of the form elements. And if you’re never going to use it, comment that I edit the code. Google Chrome problems: I tested it on Chromium. I found that the problem is that the browser does not allow including the *.js file referring to the jQuery. It is related to being a Secure HTTP address (https) but the request is not really secure. Thus, they block and the code does not validate because nothing of jQuery exists!

  • So, take a look at the answer I just posted, I was able to put a functional example on the snippet here from Sopt. The code was very small, nice, but I still don’t understand why I have to go through 3 inputs (what I’m doing)... Anyway it was worth even, besides the solution you explained legal...

  • 1

    I changed the answer, and I narrowed it down a little bit. It was only large because I thought there needed to be a check of the blank fields that required the conversation of variables of two different scopes without the apparent possibility of using global variables. He ended up eliminating a hidden element that served as a kind of global variable. In short: the scope of jQuery was not allowing me to create global within the Jsfiddle or the snippet of Stackoverflow. That is, using a hidden element to store data, I bypassed the scope of the variables "jQuery"! : ) But no longer need.

  • Man, very good, it’s already working, I’ve understood most of it, and I hardly even have the face to ask anything haha, but I still can’t understand how aniv1 becomes aniv2 mirror, and how it validated takes the data of aniv2 (I understood that it is important, and it is perfect here, until reading the data by PHP, perfect...). Is it just because the input is just below and with Hidden? Or is there something hidden in js that does this?

  • Ah.. I understand your question! Is that, as you well know, you can access the elements by JS, right? That line: document.getElementById("aniv2").value = document.getElementById("aniv1").value; takes the contents of the element with id #aniv1 and plays in #aniv2. I did it because you asked to have the type="date" and the type="text". I think it would make no difference and I think you can test with just one #aniv in addition to removing this line from JS. But to be sure, you have to test on your application. Note: I edited and commented on the code to explain the 'mirror effect'.

Show 5 more comments

Browser other questions tagged

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