2
\$\begingroup\$

This code is part of an application page, which lets user select existing or add new members, For email and Username it needs to call web services to see if they already exists then validate respectively according to business logic.

I believe this code has a lot of potential to be improved. Please note this is part of much larger code files, but I stripped it to this code only. IE-8 support is a must.

HTML

<div id="projectgPage2" class="projectg-adpage">
    <div class="projectg-form_row">
        <div class="label">
            <asp:Literal ID="litEmail" runat="server" Text="<%$Resources:ProjectG,projectgLBL_Email%>"></asp:Literal>
        </div>
        <asp:TextBox ID="txtEmail" CssClass="fullWidthInput" runat="server" ClientIDMode="Static" data-vali="-1" />
        <img id="emailValidateImg" class="projectg-images_validate" src="../images/ProjectG.ApplicationPages/wait.gif" alt="" />
        <div id="emailValidateMsg" style="display: none"> <span class="projectg-validate_msg"></span>

        </div>
    </div>
    <div class="projectg-form_row">
        <div class="label">
            <asp:Literal ID="litUsername" runat="server" Text="<%$Resources:ProjectG,projectgLBL_Username%>"></asp:Literal>
        </div>
        <asp:TextBox ID="txtUsername" CssClass="fullWidthInput" runat="server" ClientIDMode="Static" data-vali="-1" />
        <img id="usernameValidateImg" class="projectg-images_validate" src="../images/ProjectG.ApplicationPages/wait.gif" alt="" />
        <div id="usernameValidateMsg" style="display: none"> <span class="projectg-validate_msg"></span>

        </div>
    </div>
    <div class="projectg-form_row">
        <div class="label">
            <asp:Literal ID="litFirstName" runat="server" Text="<%$Resources:ProjectG,projectgLBL_FirstName%>"></asp:Literal>
        </div>
        <asp:TextBox ID="txtFirstName" CssClass="fullWidthInput" runat="server" ClientIDMode="Static" data-vali="-1" />
        <img id="firstnameValidateImg" class="projectg-images_validate" src="../images/ProjectG.ApplicationPages/wait.gif" alt="" />
        <div id="firstnameValidateMsg" style="display: none"> <span class="projectg-validate_msg"></span>

        </div>
    </div>
    <div class="projectg-form_row">
        <div class="label">
            <asp:Literal ID="litLastName" runat="server" Text="<%$Resources:ProjectG,projectgLBL_LastName%>"></asp:Literal>
        </div>
        <asp:TextBox ID="txtLastName" CssClass="fullWidthInput" runat="server" ClientIDMode="Static" data-vali="-1" />
        <img id="lastnameValidateImg" class="projectg-images_validate" src="../images/ProjectG.ApplicationPages/wait.gif" alt="" />
        <div id="lastnameValidateMsg" style="display: none"> <span class="projectg-validate_msg"></span>

        </div>
    </div>
</div> 

JS

var
selectedPage = 1,
    waitImg = "../images/ProjectG.ApplicationPages/wait.gif",
    redImg = "../images/ProjectG.ApplicationPages/red.png",
    greenImg = "../images/ProjectG.ApplicationPages/green.png",
    projectgEmailExistsTxt = "User already exists with this email, please select start date to continue",
    projectgEmailInvalidTxt = "Please enter a valid email",
    projectgUNInvalidTxt = "Please enter a valid username",
    projectgFNInvalidTxt = "Please enter a valid first name",
    projectgLNInvalidTxt = "Please enter a valid last name",
    projectgUNExistsTxt = "This username already exists, please enter a different username";

$(document).ready(function () {
    //other methods
    AddFormEvents();
    //other methods
});

function AddFormEvents() {
    var regexEmail = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;

    var $imgEmail = $("#emailValidateImg");
    var $imgUN = $("#usernameValidateImg");
    var $imgFN = $("#firstnameValidateImg");
    var $imgLN = $("#lastnameValidateImg");

    var $txtEmail = $("#txtEmail");
    var $txtUN = $("#txtUsername");
    var $txtFN = $("#txtFirstName");
    var $txtLN = $("#txtLastName");

    var ControlsAllValidate = function () {
        var valid = true;
        $.each($("[data-vali]"), function () {
            var dataValidated = $(this).attr("data-vali")
            if (dataValidated != "1") {
                valid = false;
            }
        });

        $("#projectgPageBtnAdd").attr('disabled', 'disabled');
        if (valid) $("#projectgPageBtnAdd").removeAttr('disabled');
    };
    var ValidateEmailClientSide = function (e) {
        $("#emailValidateMsg").hide().find("span").text("").removeClass("red green");
        clearTimeout(ValidateEmailClientSide.timeout);
        var ValidateEmailServerSide = function () {
            $.getJSON(_spPageContextInfo.webAbsoluteUrl + "/_vti_bin/projectg/projectg.svc/Users/Exists/", {
                email: $txtEmail.val()
            })
                .done(function (data) {
                $imgEmail.attr('src', greenImg).show();
                var $details = $(".projectg-form_row").slice(2, 5).show();
                if (data.UserExistsResult == 1) {
                    $details.hide();
                    $("#emailValidateMsg").show().find("span").text(projectgEmailExistsTxt).addClass("green");
                    $("#projectgPageBtnAdd").removeAttr('disabled');
                } else {
                    // check rest of controls are validated already ? if yes then enabled Add button
                    $txtEmail.attr('data-vali', '1');
                    ControlsAllValidate();
                }
            });
        };
        ValidateEmailClientSide.timeout = setTimeout(function () {
            $imgEmail.attr('src', waitImg).show();
            var email = $txtEmail.val();
            if (email && regexEmail.test(email)) {
                ValidateEmailServerSide();
            } else {
                $imgEmail.attr('src', redImg).show();
                $("#emailValidateMsg").show().find("span").text(projectgEmailInvalidTxt).addClass("red");
                $("#projectgPageBtnAdd").attr('disabled', 'disabled');
                $txtEmail.attr('data-vali', '-1');
                $(".projectg-form_row").slice(2, 5).show();
            }
        }, 100);
    };
    var ValidateUsernameClientSide = function (e) {
        $("#usernameValidateMsg").hide().find("span").text("").removeClass("red green");
        clearTimeout(ValidateUsernameClientSide.timeout);
        var ValidateUsernameServerSide = function () {
            $.getJSON(_spPageContextInfo.webAbsoluteUrl + "/_vti_bin/projectg/projectg.svc/Users/ExistsByUsername/", {
                username: $txtUN.val()
            })
                .done(function (data) {
                var img = greenImg;
                if (data.UsernameExistsResult) {
                    img = redImg;
                    $("#usernameValidateMsg").show().find("span").text(projectgUNExistsTxt).addClass("red");
                    $("#projectgPageBtnAdd").attr('disabled', 'disabled');
                    $txtUN.attr('data-vali', '-1');
                } else {
                    //$("#projectgPageBtnAdd").removeAttr('disabled');
                    $txtUN.attr('data-vali', '1');
                    ControlsAllValidate();
                }
                $("#usernameValidateImg").attr('src', img).show();
            })
        };
        ValidateUsernameClientSide.timeout = setTimeout(function () {
            $imgUN.attr('src', waitImg).show();
            if (!$txtUN.val()) {
                $imgUN.attr('src', redImg).show();
                $("#usernameValidateMsg").show().find("span").text(projectgUNInvalidTxt).addClass("red");
                $("#projectgPageBtnAdd").attr('disabled', 'disabled');
                $txtUN.attr('data-vali', '-1');
            } else {
                ValidateUsernameServerSide();
            }
        }, 100);
    };
    var ValidateFirstNameClientSide = function (e) {
        $("#firstnameValidateMsg").hide().find("span").text("").removeClass("red green");
        clearTimeout(ValidateFirstNameClientSide.timeout);
        ValidateFirstNameClientSide.timeout = setTimeout(function () {
            $imgFN.attr('src', waitImg).show();
            if ($txtFN.val()) {
                $imgFN.attr('src', greenImg).show();
                $txtFN.attr('data-vali', '1');
                ControlsAllValidate();
            } else {
                $imgFN.attr('src', redImg).show();
                $("#firstnameValidateMsg").show().find("span").text(projectgFNInvalidTxt).addClass("red");
                $("#projectgPageBtnAdd").attr('disabled', 'disabled');
                $txtFN.attr('data-vali', '-1');
            }
        }, 100);
    };
    var ValidateLastNameClientSide = function (e) {
        $("#lastnameValidateMsg").hide().find("span").text("").removeClass("red green");
        clearTimeout(ValidateLastNameClientSide.timeout);
        ValidateLastNameClientSide.timeout = setTimeout(function () {
            $imgLN.attr('src', waitImg).show();
            if ($txtLN.val()) {
                $imgLN.attr('src', greenImg).show();

                $txtLN.attr('data-vali', '1');
                ControlsAllValidate();
            } else {
                $imgLN.attr('src', redImg).show();
                $("#lastnameValidateMsg").show().find("span").text(projectgLNInvalidTxt).addClass("red");
                $("#projectgPageBtnAdd").attr('disabled', 'disabled');
                $txtLN.attr('data-vali', '-1');
            }
        }, 100);
    };

    $txtEmail.on('keyup paste cut', ValidateEmailClientSide);
    $txtUN.on('keyup paste cut', ValidateUsernameClientSide);
    $txtFN.on('keyup paste cut', ValidateFirstNameClientSide);
    $txtLN.on('keyup paste cut', ValidateLastNameClientSide);
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.