0

I have a login form that, when submitted, checks the username and password against a database (with c#) to confirm that the login is valid. For form validation, I'm using JavaScript, which simply checks to make sure that no fields are empty, and changes the class of elements accordingly to display a warning. I want to display these same warnings if the login is not valid as confirmed by the database, and I believe that the simplest way to do so would be to run the same JavaScript method that originally shows the validation warning after the login information is not found in the database. My current code is as follows:

Login.cshtml.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace Stride.Pages
{
    [IgnoreAntiforgeryToken(Order = 1001)]
    public class Login : PageModel
    {
        public void OnPost(string user, string pass)
        {
            if (Database.Auth(user, pass))
            {
                Response.Redirect("Index");
            }
            //if not, show the validation alert

        }
    }
}

main.js

(function ($) {
    "use strict";

    //don't allow text to lower if there is text present

    $('.input100').each(function(){
        $(this).on('blur', function(){
            if($(this).val().trim() != "") {
                $(this).addClass('has-val');
            }
            else {
                $(this).removeClass('has-val');
            }
        })
    })

    //validate input

    var input = $('.validate-input .input100');

    $('.validate-form').on('submit',function(){
        var check = true;

        for(var i=0; i<input.length; i++) {
            if(validate(input[i]) == false){
                showValidate(input[i]);
                check=false;
            }
        }

        return check;
    });

    //if focused, hide validation notification

    $('.validate-form .input100').each(function(){
        $(this).focus(function(){
            hideValidate(this);
        });
    });

    function validate (input) {
        return (!$(input).val().trim() == '');
    }

    function showValidate(input) {
        var thisAlert = $(input).parent();
        $(thisAlert).addClass('alert-validate');
    }

    function hideValidate(input) {
        var thisAlert = $(input).parent();
        $(thisAlert).removeClass('alert-validate');
    }

})(jQuery);

Login.cshtml

@page
@model Stride.Pages.Login

@{
    Layout = null;
}

<head>
    <title>Log in to your account</title>
    <link rel="shortcut icon" href="images/icons/favicon.ico" type="image/x-icon"/>
    <link rel="stylesheet" type="text/css" href="css/main.css">
</head>
<body>
<div class="limiter">
    <div class="container-login100">
        <div class="wrap-login100">
            <form class="login100-form validate-form" method="post">
                <span class="login100-form-title" style="padding-bottom: 28px">
                    Welcome
                </span>
                <span class="login100-form-title" style="padding-bottom: 48px">
                    <i class="zmdi zmdi-font"></i>
                </span>

                <div class="wrap-input100 validate-input" data-validate="Check Username">
                    <input class="input100" type="text" name="user">
                    <span class="focus-input100" data-placeholder="Username"></span>
                </div>

                <div class="wrap-input100 validate-input" data-validate="Check Password">
                    <input class="input100" type="password" name="pass">
                    <span class="focus-input100" data-placeholder="Password"></span>
                </div>

                <div class="container-login100-form-btn">
                    <div class="wrap-login100-form-btn">
                        <div class="login100-form-bgbtn"></div>
                        <button class="login100-form-btn" type="submit">
                            Login
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
<script src="js/jquery/jquery-3.2.1.min.js"></script>
<script src="js/main.js"></script>
</body>

Any help is appreciated, or if there's a better way to handle validation without using JavaScript that I'm not picking up on (i.e. all validation is with the c#, and I'm able to change the element class directly from c#) let me know. Thanks!

2
  • 2
    If the log in is not valid have the server return 401 unauthorized. Commented Dec 19, 2019 at 21:35
  • You probably want to do an ajax call with javascript and have the server return the result, then javascript can do whatever it wants with it. Alternatively, you could always look into using Blazor in your project, which can call javascript from c# with JsInterop, but there could be significant effort involved to convert your project. Commented Dec 20, 2019 at 0:16

1 Answer 1

1

You can't run JS directly from the C# code as of right now. You could post the data with AJAX, have it return a boolean, and then load the new page or show the validation error as needed. I'd prefer to keep the login all occurring on the backend, though.

I'd implement a property in ViewData, something like ViewData["InvalidLogin"]. In your login action, if the validation fails, set that equal to the validation failed class alert-validate. Then in the view, add @ViewData["InvalidLogin"] to the class list of the validation error elements.

// PageModel
public IActionResult OnPost(string user, string pass)
{
    if (Database.Auth(user, pass))
    {
        Response.Redirect("Index");
    }

    ViewData["InvalidLogin"] = "alert-validate";
    return Page();
}

// Razor Page
<div class="wrap-input100 validate-input @ViewData["InvalidLogin"]" data-validate="Check Username">

On initial load, this will not apply any extra class. It will only add the extra class if the validation fails and you send the page back to the browser.

I realized halfway through this you're using Razor Pages, so apologies if anything here is more MVC focused.

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

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.