How to execute a function only if the input has something typed?

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 ... But I would like to know how to do when the input is EMPTY, and I click on the "Send" button it does nothing, it does not even look yellow and does not appear under the message " Please enter a valid CPF ". ...

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

I tried to use an If, but I'm new and I could not:

$('#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('');    
                        }
                        }
                }); 

The full example below follows:

/*============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><inputclass="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>
    
asked by anonymous 20.01.2018 / 18:00

2 answers

-1

I made a change 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><inputclass="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>
    
20.01.2018 / 18:11
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 white spaces in the field. The regular expression % with% looks for all white space. So, if the user types only whitespace in the field, this /\s/g 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 Boolean check, which returns true (field with some character-value or space, or false when you have nothing:

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

Therefore, there is no need for if , which only checks if the field is not empty.

    
21.01.2018 / 15:21