3
\$\begingroup\$

I'm doing some simple validations using jQuery to check if all textboxes are filled.

$(document).ready(function () {
$("#<%= btnInsertCountry.ClientID %>").click(function () {
    var codeValue = $("#<%= txtCountryCode.ClientID %>").val();
    var nameValue = $("#<%= txtCountryName.ClientID %>").val();

    if (codeValue == "" || nameValue == "") {
        if (codeValue == "") {
            $("#divCodeValidation").show();
        }
        else {
            $("#divCodeValidation").hide();
        }

        if (nameValue == "") {
            $("#divNameValidation").show();
        }
        else {
            $("#divNameValidation").hide();
        }

        return;
    }
});
});

The divs have the property display: none and contains the error message. This code works but I don't like it because I use an if to check if the values are empty and inside I have an if for each variable.

Is there a better way to do this validation?

\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

The two validations are independent. There's no point to if (codeValue == "" || nameValue == "") { … }.


Instead of calling $.show() and $.hide(), use $.toggle(display):

display
Type: Boolean
Use true to show the element or false to hide it.


You can also write $(function() { … }) instead of $(document).ready(function() { … }).


$(function () {    
    $("#<%= btnInsertCountry.ClientID %>").click(function () {
        $("#divCodeValidation").toggle(
            "" == $("#<%= txtCountryCode.ClientID %>").val()
        );
        $("#divNameValidation").toggle(
            "" == $("#<%= txtCountryName.ClientID %>").val()
        );
    });
});
\$\endgroup\$
0
\$\begingroup\$

Your If statement is checking for "" twice unnecessarily:

$(document).ready(function () {
$("#<%= btnInsertCountry.ClientID %>").click(function () {
    var codeValue = $("#<%= txtCountryCode.ClientID %>").val();
    var nameValue = $("#<%= txtCountryName.ClientID %>").val();

 if (codeValue == "") {
        $("#divCodeValidation").show();
    }
    else {
        $("#divCodeValidation").hide();
    }

    if (nameValue == "") {
        $("#divNameValidation").show();
    }
    else {
        $("#divNameValidation").hide();
    }

    return;

});
});
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.