0

I am programming a website as a part of my own project, and I have a registration form with a javascript validating first the email, password, fname, and etc and only then it submits the form. From there the c# takes over and checks if there is a user with such username in the database, and if there's I want to show an error as a paragraph in the registration form or show alert using JS.

Website:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="register.aspx.cs" Inherits="EquimaxSchool.register" %>

    <section class="login-dark">
    <form id="register" runat="server" method="post" >
            <h2 class="sr-only">Login Form</h2>
            <div class="illustration"><i class="icon ion-ios-locked-outline"></i></div>
            <div class="form-group"><input class="form-control" type="text" name="username" placeholder="Username" runat="server" id="username"/></div> <!-- Username #11 -->
            <div class="form-group"><input class="form-control" type="text" name="email" placeholder="Email" runat="server" id="email"></div> <!-- Email #1 -->
            <div class="form-group"><input class="form-control" type="password" name="password" placeholder="Password" runat="server" id="password"></div> <!-- Password #2 -->
            <div class="form-group"><input class="form-control" type="text" name="fName" placeholder="First Name" runat="server" id="fName" /></div> <!-- First Name #8 -->
            <div class="form-group"><input class="form-control" type="text" name="lName" placeholder="Last Name" runat="server" id="lName" required/></div> <!-- Last Name #9 -->
            <div class="form-group"><input class="form-control" type="date" name="birthdate" runat="server" id="birthdate" placeholder="Birthdate" required/></div> <!-- Birthdate #3 -->
            <div class="form-group"><input class="form-control" title="Phone Number" name="phonenumber" placeholder="Phone Number" runat="server" id="phonenumber" /></div> <!-- Phone Number #4 -->
            <span></span>
            <div class="form-group"><select id="gender" name="gender" class="form-control" style="color:#6c757d" required>
                                        <option value="Gender" disabled="disabled" selected="selected">Gender</option>
                                        <option value="Male">Male</option>
                                        <option value="Female">Female</option>
                                        <option value="Other">Other</option>
            </select></div>
            <div class="form-group"><select id="camera" name="camera-brand" class="form-control" style="color:#6c757d" required>
                                        <option value="Camera Brand" disabled="disabled" selected="selected">Camera Brand</option>
                                        <option value="Nikon">Nikon</option>
                                        <option value="Canon">Canon</option>
                                        <option value="Fuji">Fuji</option>
                                        <option value="Sony">Sony</option>
                                        <option value="Other">Other</option>
            </select></div>
            <div class="form-group"><input class="form-control" type="text" name="lens" placeholder="Lens" id="lens"/></div> <!-- Lens #10 -->
            <div class="form-group"><select id="genre" name="genre" runat="server" class="form-control" style="color:#6c757d" required>
                                    <option value="Sport">Sports</option>
                                    <option value="Wildlife">Wildlife</option>
                                    <option value="Landscape">Landscape</option>
                                    <option value="Portrait">Portrait</option>
                                    <option value="Architecture">Architecture</option>
            </select></div>
            <div class="form-group"><button class="btn btn-primary btn-block" type="submit" runat="server" id="submit">Sign up</button></div>
        <%= msg %> <===== **THIS IS WHERE THE ERROR OCCURS**
        </form>

(Please note I've redacted unnecessary tags and etc)

The JS of validation of form:

        <script lang="javascript" type="text/javascript">
            function validationCheck() {
                var summary = "";
                summary += isvalidpassword();
                summary += isvalidFirstname();
                summary += isvalidEmail();
                summary += isvalidphoneno();
                if (summary != "") {
                    alert(summary);
                    return false;
                } else {
                    return true;
                }
            }

            function isvalidpassword() {
                var id;
                var temp = document.getElementById("password");
                id = temp.value;
                if (id == "") {
                    return ("Password can't be empty" + "\n");
                } else if (id.length > 1 && id.length < 8) {
                    return ("Password can't be shorter than 8" + "\n");
                } else {
                    return "";
                }
            }

            function isvalidFirstname() {
                var id;
                var temp = document.getElementById("fName");  
                id = temp.value;  
                if (id == "") {  
                    return ("First name can't be empty" + "\n");  
                } else {  
                    return "";  
                }  
            }  
  
            function isvalidEmail() {  
                var id;  
                var temp = document.getElementById("email");  
                id = temp.value;  
                var re = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;  
                if (id == "") {  
                    return ("Email can't be empty" + "\n");  
                } else if (re.test(id)) {  
                    return "";  
                } else {  
                    return ("Email invalid" + "\n");  
                }  
            }  
  
            function isvalidphoneno() {  
                var id;  
                var temp = document.getElementById("phonenumber");  
                id = temp.value;  
                var re;  
                re = /^[0-9]+$/;  
                var digits = /\d(10)/;  
                if (id == "") {  
                    return ("Phone number can't be empty" + "\n");  
                } else if (re.test(id)) {  
                    return "";  
                } else {  
                    return ("Phone number should be digits only" + "\n");  
                }  
            }

            $(document).ready(function () {
                $("#register").submit(function (event) {
                    if (!validationCheck()) {
                        event.preventDefault();
                    }
                });
            });
        </script>

The code behind it:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace EquimaxSchool
{
    public partial class register : System.Web.UI.Page
    {
        public string msg = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Form["submit"] != null)
            {
                string email = Request.Form["email"];
                string password = Request.Form["password"];
                string gender = Request.Form["gender"];
                string fName = Request.Form["fName"];
                string lName = Request.Form["lName"];
                string phoneNumber = Request.Form["phonenumber"];
                string camera = Request.Form["camera-brand"];
                string birthdate = Request.Form["birthdate"];
                string genre = Request.Form["genre"];
                string username = Request.Form["username"];
                string fileName = "UsersData.mdf";
                string tableName = "usersTbl";
                string sqlSelect = "SELECT * FROM " + tableName + " WHERE Username = '" + username + "'";

                if (Helper.IsExist(fileName, sqlSelect))
                {
                    msg = "Username has been taken already.";
                }
            }
            
            
        }
    }
}

Helper.cs for those asking


using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

/// <summary>
/// Summary description for Helper
/// </summary>
/// 


public class Helper
{     
    public static SqlConnection ConnectToDb(string fileName)
    {
            string path = HttpContext.Current.Server.MapPath("App_Data/") + fileName;
        //string connString = @"Data Source=.\SQLEXPRESS;AttachDbFileName=" + path + ";Integrated Security=True;User Instance=True";
        //string connString = @"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = |DataDirectory|\" + fileName + " Integrated Security = True";
        //string connString = @"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = " + path + " Integrated Security = True";
        
        //string connString = @"";
        
        string connString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=" + path + ";Integrated Security=True;Connect Timeout=30";
        
        SqlConnection conn = new SqlConnection(connString);
            return conn;
    }

    public static void DoQuery(string fileName, string sql)
    {
        SqlConnection conn = ConnectToDb(fileName);
        conn.Open();
        SqlCommand com = new SqlCommand(sql, conn);
        com.ExecuteNonQuery();
        conn.Close();
    }



    public static bool IsExist(string fileName, string sql)
    {

        SqlConnection conn = ConnectToDb(fileName);
        conn.Open();
        SqlCommand com = new SqlCommand(sql, conn);
        SqlDataReader data = com.ExecuteReader();

        bool found = Convert.ToBoolean(data.Read());
        conn.Close();
        return found;

    }

    public static DataTable ExecuteDataTable(string fileName, string sql)
    {
        SqlConnection conn = ConnectToDb(fileName);
        conn.Open();

        DataTable dt = new DataTable();

        SqlDataAdapter tableAdapter = new SqlDataAdapter(sql, conn);

        tableAdapter.Fill(dt);


        return dt;
    }

}



https://i.stack.imgur.com/b5GmQ.png

1 Answers1

0

Your page inherits the class 'EquimaxSchool.login'

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="register.aspx.cs" Inherits="EquimaxSchool.login" %>

However, your C# class is named 'EquimaxSchool.Webform1'

namespace EquimaxSchool
    {
        public partial class WebForm1 : System.Web.UI.Page
        {

Have you shown us the correct codebehind file? Is there a class called 'login' in the register.aspx.cs file?

JHW
  • 124
  • 1
  • 11
  • Yeah seems like there is an error with the name of the original aspx webform file and the class in the register.aspx.cs. – Max Ilyouchenko Dec 26 '21 at 09:55
  • have a look at this answer https://stackoverflow.com/a/1671836/1372848 – JHW Dec 26 '21 at 09:56
  • I've made a fix and changed everything incorrect in the C# class, but the paragraph with the message doesn't appear. – Max Ilyouchenko Dec 26 '21 at 09:57
  • I've fixed that problem, now the only problem that persists is that I can't show a message or anything in the HTML. – Max Ilyouchenko Dec 26 '21 at 10:00
  • Can you update your question with the changes you have made? Try setting the initial value of msg to something other than "" (just to see if it appears). Also - try checking the page source of the html produced - your text may be there but not visible in the browser (you haven't shown us any CSS that is being applied). – JHW Dec 26 '21 at 10:10
  • I have updated the question with the changes just now, Check it out. I've tried setting the msg to "Hello" and it did show up, but when purposely trying to register with an existing username, the text doesn't change. – Max Ilyouchenko Dec 26 '21 at 10:17
  • Ok, in that case if (Helper.IsExist(fileName, sqlSelect)) is not evaluating to true. Have you tried using a debugger to see what is happening in the code? Without knowing what Helper.IsExist does (or the content of your databas) it's difficult to help further. – JHW Dec 26 '21 at 10:21
  • The debugger doesn't print out anything, I'll try printing the content of "username" field using C# into the debugger, check maybe the problem is there. The Helper.isExist just check if there exists anything when using the SQL query in the DB file. – Max Ilyouchenko Dec 26 '21 at 10:25
  • I've tried printing the content of "username" field using `System.Diagnostics.Debug.WriteLine(...)` and tried printing "Inside the if condition" using `System.Diagnostics.Debug.WriteLine(...)` when it checks if it really happens. – Max Ilyouchenko Dec 26 '21 at 10:28
  • Where does 'Helper.IsExist' come from? Is this your code? Try setting your sql query to something that will ALWAYS return something to test it - something like string sqlSelect = "SELECT 'HelloWorld'"; – JHW Dec 26 '21 at 10:29
  • Helper.IsExist comes from an external file that I've got whose mission is to help me with these SQL queries. I will upload it there into the post I made. – Max Ilyouchenko Dec 26 '21 at 10:33
  • I think your problem is with the IsExist method. Take a look at this https://stackoverflow.com/q/1540613/1372848. I would suggest you start another question for this if you need more help, as the title and tags for this question are now very misleading. This is not an issue with javascript or html but with how you are using System.Data.SqlClient. – JHW Dec 26 '21 at 10:43