1

I have to execute a authentication process using JQuery. I have two textbox UserName and Password and two button are Login and Submit.

If i am clicking on Submit button then it will automatically fire validation that good and this functionality i have to implement on Login button click.

So how could i achieve automatic validation on button click?

Why i would like this:

  1. Usin JQuery it is sending a request to the server with UserName and Password during that time i will display Processing....
  2. Then it will verify supplied value with database and return response with Success or Failed then i will display either Success or Failed.

Here is the code snippet:

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.")
@using (Html.BeginForm(null, null, FormMethod.Get, new { id = "Form1", name = "Form1" }))
{
    <table>
        <tr>
            <td>
                User Name
            </td>
            <td>@Html.TextBoxFor(u => u.UserName, new { id = "txtUser" }) @Html.ValidationMessageFor(u => u.UserName)
            </td>
        </tr>
        <tr>
            <td>
                Password
            </td>
            <td>@Html.TextBoxFor(u => u.Password, new { id = "txtPassword" })  @Html.ValidationMessageFor(u => u.Password)
            </td>
        </tr>
        <tr>
            <td>
            </td>
            <td>
                <input type="button" value="Login" onclick="checkAuthentication();" />
                <input type="submit" value="Submit" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <div id="dvStatus" class="loginMessageStatus">
                </div>
            </td>
        </tr>
    </table>
}
<script language="javascript" type="text/javascript">
    function getUserCredentials() {
        var user = jQuery('#txtUserName').val();
        var pass = jQuery('#txtPassword').val();
        return { UserName: user, Password: pass };
    }
    function clearUserCredentials() {
        jQuery('#txtUserName').val("");
        jQuery('#txtPassword').val("");
        jQuery('#txtUserName').focus();
    }
    function checkAuthentication() {
            jQuery('#dvStatus').html("<div class='requestProcess'></div><div class='requestMessage'>Please wait...</div>")
            var postData = getUserCredentials();
            var ajaxResponse = $.ajax({
                type: "post",
                url: '@Url.Action("Index", "Login")',
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(postData),
                success: function (result) {
                    var res = jQuery.parseJSON(result);
                    if (res.Success == true) {
                        jQuery('#dvStatus').html("<div class='requestSuccess'></div><div class='requestMessage'>Your are successfully logged in. Redirecting...</div>")
                        jQuery.doTimeout(100, redirectToPage);
                    }
                    else {
                        jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>Error: " + res.Message + ". <a href='javascript:void(0)' onclick='clearUserCredentials()'>Try Again</a></div>")
                    }
                }
            });
    }
    function redirectToPage() {
        href = '@Url.Action("Index", "TabMaster")';
        window.location.href = href;
    }

Note:-

  1. Validation completely work with Submit button
  2. Verifying process completely work with Login button ( just i have to integrate validation with Login button)
3
  • It looks like the code would work, are you looking for the code on the controller? I am not sure what you are looking for? Commented Jul 30, 2011 at 7:25
  • There's no need to put [solved] in your question title. Just accept your own answer (when you can) and this will mark the question in on the home page so everyone can see it's status. Commented Jul 30, 2011 at 10:29
  • Nice comment, unfortunately it will gives me following message "You can accept your own answer in 2 days" so decided to kept it with solved for at-least two days then i will make it to Correct Answer. Commented Jul 30, 2011 at 10:50

2 Answers 2

4

you can do the validation using the onclick of the submit button with the following event handler:

Add an identifier to the button:

<input id="SubmitButton" type="submit" value="Submit" />

JavaScript:

$(document).ready(function(){
    $("#SubmitButton").click(function(){
         return checkAuthentication();
    });
});

Change the Validation method to return whether it failed or not:

function checkAuthentication() {
    var _user = jQuery.trim(jQuery('#txtUserName').val());
    var _pass = jQuery.trim(jQuery('#txtPassword').val());
    if (_user.length == 0 || _pass.length == 0) {
        jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>User Name and Password are required!</div>")
        return false;
    }
    else {
        jQuery('#dvStatus').html("<div class='requestProcess'></div><div class='requestMessage'>Please wait...</div>")
        var postData = getUserCredentials();
        var ajaxResponse = $.ajax({
            type: "post",
            url: '@Url.Action("Index", "Login")',
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(postData),
            success: function (result) {
                var res = jQuery.parseJSON(result);
                if (res.Success == true) {
                    jQuery('#dvStatus').html("<div class='requestSuccess'></div><div class='requestMessage'>Your are successfully logged in. Redirecting...</div>")
                    jQuery.doTimeout(100, redirectToPage);
                }
                else {
                    jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>Error: " + res.Message + ". <a href='javascript:void(0)' onclick='clearUserCredentials()'>Try Again</a></div>")
                }
            }
        });
        return true;
    }
}

This should then stop the submit if the validation fails.

Sign up to request clarification or add additional context in comments.

1 Comment

How were you planning on checking validation other than with a onclick event handler? Or is it using the check validation method because you could make sure that there is values in the field and stop the submit that way?
0

I have solved this one: I have used only submit button

<input id="btnLogin" type="submit" value="Login" />

Following are the updated code

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        //$.preloadCssImages();
        $("#btnLogin").click(function () {
            if ($("#Form1").valid() == true) {
                checkAuthentication();
                return false;
            }
        });
    });
    function getUserCredentials() {
        var user = jQuery('#txtUserName').val();
        var pass = jQuery('#txtPassword').val();
        return { UserName: user, Password: pass };
    }
    function clearUserCredentials() {
        jQuery('#txtUserName').val("");
        jQuery('#txtPassword').val("");
        jQuery('#txtUserName').focus();
    }
    function checkAuthentication() {
        jQuery('#dvStatus').html("<div class='requestProcess'></div><div class='requestMessage'>Please wait...</div>")
        var postData = getUserCredentials();
        var ajaxResponse = $.ajax({
            type: "post",
            url: '@Url.Action("Index", "Login")',
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(postData),
            success: function (result) {
                var res = jQuery.parseJSON(result);
                if (res.Success == true) {
                    jQuery('#dvStatus').html("<div class='requestSuccess'></div><div class='requestMessage'>Your are successfully logged in. Redirecting...</div>")
                    jQuery.doTimeout(100, redirectToPage);
                }
                else {
                    jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>Error: " + res.Message + ". <a href='javascript:void(0)' onclick='clearUserCredentials()'>Try Again</a></div>")
                }
            }
        });
    }
    function redirectToPage() {
        href = '@Url.Action("Index", "TabMaster")';
        window.location.href = href;
    }
</script>

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.