How to execute a function only if the input is typed?

Asked

Viewed 114 times

0

I have this script for CPF validation:

$('#cpf').cpfcnpj({
                    mask: true,
                    validate: 'cpf',
                    event: 'click',
                    handler: '.btn-lg',
                    ifValid: function (input) {
                        input.removeClass("error");
                        $('#erro-cpf').html('');                          
                    },
                    ifInvalid: function (input) { 
                        input.addClass("error");
                        $('#erro-cpf').html('Digite um CPF válido');                         
                    }                    
                });

It works perfectly... However I would like to know how to do it for when the input is EMPTY, and I click on the "Send" button it does nothing, like neither turn yellow nor appear below the message "Type a valid CPF". ...

Get it?! I want the script to only display "Enter a valid CPF" message when you have something typed in the input, if it is empty nothing happens.

I tried to use an If, but I’m new and I couldn’t:

$('#cpf').cpfcnpj({
                    mask: true,
                    validate: 'cpf',
                    event: 'click',
                    handler: '.btn-lg',                    
                    ifValid: function (input) {
                        input.removeClass("error");
                        $('#erro-cpf').html('');                          
                    },
                    ifInvalid: function (input) { 
                        input.addClass("error");                        
                        $('#erro-cpf').html('Digite um CPF válido');
                        if('cpf' === null){
                        $('#erro-cpf').html('');    
                        }
                        }
                }); 

follows below the complete example:

/*============FUNCAO Q VALIDA CPF==============*/
(function(e) {
    function n(e) {
        if (e.match(/^\d{2}\.\d{3}\.\d{3}\/\d{4}\-\d{2}$/) != null) {
            var t = e.substring(0, 2);
            var n = e.substring(3, 6);
            var r = e.substring(7, 10);
            var i = e.substring(11, 15);
            var o = e.substring(16, 18);
            var u;
            var a;
            var f = true;
            a = t + n + r + i + o;
            s = a;
            c = s.substr(0, 12);
            var l = s.substr(12, 2);
            var h = 0;
            for (u = 0; u < 12; u++) h += c.charAt(11 - u) * (2 + u % 8);
            if (h == 0) f = false;
            h = 11 - h % 11;
            if (h > 9) h = 0;
            if (l.charAt(0) != h) f = false;
            h *= 2;
            for (u = 0; u < 12; u++) {
                h += c.charAt(11 - u) * (2 + (u + 1) % 8)
            }
            h = 11 - h % 11;
            if (h > 9) h = 0;
            if (l.charAt(1) != h) f = false;
            return f
        }
        return false
    }

    function r(e) {
        if (e.match(/^\d{3}\.\d{3}\.\d{3}\-\d{2}$/) != null) {
            var t = e.substring(0, 3);
            var n = e.substring(4, 7);
            var r = e.substring(8, 11);
            var i = e.substring(12, 14);
            var o;
            var u;
            var a = true;
            u = t + n + r + i;
            s = u;
            c = s.substr(0, 9);
            var f = s.substr(9, 2);
            var l = 0;
            for (o = 0; o < 9; o++) {
                l += c.charAt(o) * (10 - o)
            }
            if (l == 0) a = false;
            l = 11 - l % 11;
            if (l > 9) l = 0;
            if (f.charAt(0) != l) a = false;
            l *= 2;
            for (o = 0; o < 9; o++) {
                l += c.charAt(o) * (11 - o)
            }
            l = 11 - l % 11;
            if (l > 9) l = 0;
            if (f.charAt(1) != l) a = false;
            return a
        }
        return false
    }
    var t = null;
    e.fn.cpfcnpj = function(i) {
        var s = e.extend({
            mask: false,
            validate: "cpfcnpj",
            event: "focusout",
            handler: e(this),
            ifValid: null,
            ifInvalid: null
        }, i);
        if (s.mask) {
            if (jQuery().mask == null) {
                s.mask = false;
                console.log("jQuery mask not found.")
            } else {
                if (s.validate == "cpf") {
                    e(this).mask("000.000.000-00")
                } else if (s.validate == "cnpj") {
                    e(this).mask("00.000.000/0000-00")
                } else {
                    var o = e(this);
                    var u = {
                        onKeyPress: function(e) {
                            var t = ["000.000.000-009", "00.000.000/0000-00"];
                            msk = e.length > 14 ? t[1] : t[0];
                            o.mask(msk, this)
                        }
                    };
                    e(this).mask("000.000.000-009", u)
                }
            }
        }
        return this.each(function() {
            var i = null;
            var o = e(this);
            e(document).on(s.event, s.handler, function() {
                if (o.val().length == 14 || o.val().length == 18) {
                    if (s.validate == "cpf") {
                        i = r(o.val())
                    } else if (s.validate == "cnpj") {
                        i = n(o.val())
                    } else if (s.validate == "cpfcnpj") {
                        if (r(o.val())) {
                            i = true;
                            t = "cpf"
                        } else if (n(o.val())) {
                            i = true;
                            t = "cnpj"
                        } else i = false
                    }
                } else i = false;
                if (e.isFunction(s.ifValid)) {
                    if (i != null && i) {
                        if (e.isFunction(s.ifValid)) {
                            var u = e.Callbacks();
                            u.add(s.ifValid);
                            u.fire(o)
                        }
                    } else if (e.isFunction(s.ifInvalid)) {
                        s.ifInvalid(o)
                    }
                }
            })
        })
    }
})(jQuery)


/* ==MUDA COR DA BORDA SE O CPF FOR FALSE===*/
$(document).ready(function () {
                $('#cpf').cpfcnpj({
                    mask: false,
                    validate: 'cpf',
                    event: 'click',
                    handler: '.btn-lg',
                    ifValid: function (input) {
                        input.removeClass("error");
                        $('#erro-cpf').html('');
                    },
                    ifInvalid: function (input) {
                        $('#erro-cpf').html('Digite um CPF válido');
                        input.addClass("error");
                    }
                });
            });
.error { border-color: #fff600 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input class="form-control" id="cpf" type="tel" placeholder="CPF" required>
<button class="btn-lg btn-primary form-control" type="submit">Enviar</button>
<div class"error" id="erro-cpf"></div>

2 answers

0

One way to optimize this check is by using the syntax below:

if( $('#cpf').val().replace(/\s/g,'') ){
    // campo CPF não vazio
}

The .replace(/\s/g,'') deletes all blank spaces from the field. A regular expression /\s/g searches for all whitespace. Thus, if the user only enters whitespace in the field, this if will not validate, unlike if below, which only checks if the field is not empty and will validate if there is only space:

if( $('#cpf').val() != '' ) {
    // campo CPF não vazio
}

Another point is redundancy. To check if the field is empty, just do a check boolean, returning true (field with some value -- character or space, or false when there’s nothing:

if( $('#cpf').val() ) { // verifica se o valor é true, ou seja, tem algo
    // campo CPF não vazio
}

Therefore, there is no need to != '', which only checks that the field is not empty.

  • very good tbm, I modified the code with this tip of yours ;) ... vlwww

  • @Danielfortunato Hi Daniel. I wanted to ask a question: you found the other answer better?

-1


I made a modification to your if. So it will only add the text and class if the Cpf field is not empty.

if($('#cpf').val() != '') {
     $('#erro-cpf').html('Digite um CPF válido');
     input.addClass("error");
}

/*============FUNCAO Q VALIDA CPF==============*/
(function(e) {
    function n(e) {
        if (e.match(/^\d{2}\.\d{3}\.\d{3}\/\d{4}\-\d{2}$/) != null) {
            var t = e.substring(0, 2);
            var n = e.substring(3, 6);
            var r = e.substring(7, 10);
            var i = e.substring(11, 15);
            var o = e.substring(16, 18);
            var u;
            var a;
            var f = true;
            a = t + n + r + i + o;
            s = a;
            c = s.substr(0, 12);
            var l = s.substr(12, 2);
            var h = 0;
            for (u = 0; u < 12; u++) h += c.charAt(11 - u) * (2 + u % 8);
            if (h == 0) f = false;
            h = 11 - h % 11;
            if (h > 9) h = 0;
            if (l.charAt(0) != h) f = false;
            h *= 2;
            for (u = 0; u < 12; u++) {
                h += c.charAt(11 - u) * (2 + (u + 1) % 8)
            }
            h = 11 - h % 11;
            if (h > 9) h = 0;
            if (l.charAt(1) != h) f = false;
            return f
        }
        return false
    }

    function r(e) {
        if (e.match(/^\d{3}\.\d{3}\.\d{3}\-\d{2}$/) != null) {
            var t = e.substring(0, 3);
            var n = e.substring(4, 7);
            var r = e.substring(8, 11);
            var i = e.substring(12, 14);
            var o;
            var u;
            var a = true;
            u = t + n + r + i;
            s = u;
            c = s.substr(0, 9);
            var f = s.substr(9, 2);
            var l = 0;
            for (o = 0; o < 9; o++) {
                l += c.charAt(o) * (10 - o)
            }
            if (l == 0) a = false;
            l = 11 - l % 11;
            if (l > 9) l = 0;
            if (f.charAt(0) != l) a = false;
            l *= 2;
            for (o = 0; o < 9; o++) {
                l += c.charAt(o) * (11 - o)
            }
            l = 11 - l % 11;
            if (l > 9) l = 0;
            if (f.charAt(1) != l) a = false;
            return a
        }
        return false
    }
    var t = null;
    e.fn.cpfcnpj = function(i) {
        var s = e.extend({
            mask: false,
            validate: "cpfcnpj",
            event: "focusout",
            handler: e(this),
            ifValid: null,
            ifInvalid: null
        }, i);
        if (s.mask) {
            if (jQuery().mask == null) {
                s.mask = false;
                console.log("jQuery mask not found.")
            } else {
                if (s.validate == "cpf") {
                    e(this).mask("000.000.000-00")
                } else if (s.validate == "cnpj") {
                    e(this).mask("00.000.000/0000-00")
                } else {
                    var o = e(this);
                    var u = {
                        onKeyPress: function(e) {
                            var t = ["000.000.000-009", "00.000.000/0000-00"];
                            msk = e.length > 14 ? t[1] : t[0];
                            o.mask(msk, this)
                        }
                    };
                    e(this).mask("000.000.000-009", u)
                }
            }
        }
        return this.each(function() {
            var i = null;
            var o = e(this);
            e(document).on(s.event, s.handler, function() {
                if (o.val().length == 14 || o.val().length == 18) {
                    if (s.validate == "cpf") {
                        i = r(o.val())
                    } else if (s.validate == "cnpj") {
                        i = n(o.val())
                    } else if (s.validate == "cpfcnpj") {
                        if (r(o.val())) {
                            i = true;
                            t = "cpf"
                        } else if (n(o.val())) {
                            i = true;
                            t = "cnpj"
                        } else i = false
                    }
                } else i = false;
                if (e.isFunction(s.ifValid)) {
                    if (i != null && i) {
                        if (e.isFunction(s.ifValid)) {
                            var u = e.Callbacks();
                            u.add(s.ifValid);
                            u.fire(o)
                        }
                    } else if (e.isFunction(s.ifInvalid)) {
                        s.ifInvalid(o)
                    }
                }
            })
        })
    }
})(jQuery)


/* ==MUDA COR DA BORDA SE O CPF FOR FALSE===*/
$(document).ready(function () {
                $('#cpf').cpfcnpj({
                    mask: false,
                    validate: 'cpf',
                    event: 'click',
                    handler: '.btn-lg',
                    ifValid: function (input) {
                        input.removeClass("error");
                        $('#erro-cpf').html('');
                    },
                    ifInvalid: function (input) {
                        if($('#cpf').val() != '') {
                          $('#erro-cpf').html('Digite um CPF válido');
                          input.addClass("error");
                        }
                    }
                });
            });
.error { border-color: #fff600 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input class="form-control" id="cpf" type="tel" placeholder="CPF" required>
<button class="btn-lg btn-primary form-control" type="submit">Enviar</button>
<div class"error" id="erro-cpf"></div>

  • tried this way and it didn’t work either :(

  • Put as your code did with this example of mine.

  • thus: https://jsfiddle.net/7qyn9oxd/

  • You have to leave the text line and error class only inside if. I edited my post and left a full code example.

  • Thanks a lot for the help guy, agr worked yes, I’m new and I’m catching a lot.. thank you very much indeed.

Browser other questions tagged

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