Need help in login validation using javascript - asp.net

Please could somebody point me out what is the error here? Using javascript i am validating the user input. When i click the login button without checking the javascript function, it goes to the welcome page. Here is my code:
<script type="text/javascript">
function validLogin()
{
if(document.getElementById("txtUserName").value == "")
{
alert("Please enter your UserName");
return false;
}
if(document.getElementById("txtPassword").value == "")
{
alert("Please enter your Password");
return false;
}
}
</script>
protected void Page_Load(object sender, EventArgs e)
{
BtnLogin.Attributes.Add("onClick","return ValidLogin();");
}

I see that you're using ASP .NET (the Page_Load event on your posted code).
I think that will be easier to handle validation through ASP .NET Validation Controls, i.e. RequiredFieldValidator.

Check your case on return ValidLogin(); it doesn't match.
P.S.: I hope you aren't performing all user validation client-side.

It would probably be easier to user ASP .NET validation controls, here's a sample:
User Name:
<asp:TextBox ID="UserName" runat="server" />
<asp:RequiredFieldValidator
ID="UserNameValidator"
ControlToValidate="UserName"
ErrorMessage="User Name Required"
runat="server" />
Password:
<asp:TextBox ID="Password" runat="server" />
<asp:RequiredFieldValidator
ID="PasswordValidator"
ControlToValidate="Password"
ErrorMessage="Password Required"
runat="server" />

first make sure it's not a difference in case... your javascript function is validLogin and in Page_Load you have ValidLogin

Related

How to avoid Page_Load() on button click?

I have two buttons, preview and Save. With help of preview button user can view the data based on the format and then can save.
But when preview is clicked, one textbox attached to ajaxcontrol (Calender) becomes empty and user have to fill the date before saving. How to handle this? On preview click i get the details to show the data in layout.
<asp:TextBox ID="txtDate" ReadOnly="true" runat="server"></asp:TextBox>
<div style="float: right;">
<asp:ImageButton ID="imgcalender1" runat="server" ImageUrl="~/images/calendar.png"
ImageAlign="Bottom" />
<asp:CalendarExtender ID="ajCal" TargetControlID="txtpublishDate" PopupButtonID="imgcalender1"
runat="server">
</asp:CalendarExtender>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" ValidationGroup="group1" runat="server" ControlToValidate="txtDate"
ForeColor="Red" Font-Bold="true" ErrorMessage="*"></asp:RequiredFieldValidator>
</div>
<asp:Button ID="btnPreview" runat="server" Text="Preview" OnClick="btnPreview_Click" />
<asp:Button ID="btnsubmit" runat="server" ValidationGroup="group1" Text="Save" OnClick="btnsubmit_Click" />
Use Page.IsPostback() in your aspx code (server-side). Like this:
private void Page_Load()
{
if (!IsPostBack)
{
// the code that only needs to run once goes here
}
}
This code will only run the first time the page is loaded and avoids stepping on user-entered changes to the form.
From what I am understanding the preview button is causing a postback and you do not want that, try this on your preview button:
<asp:button runat="server".... OnClientClick="return false;" />
similarly this also works:
YourButton.Attributes.Add("onclick", return false");
Edit:
it seems the answer to the user's question was simple change in the HTML mark up of the preview button
CausesValidation="False"
you can put your code in
Page_Init()
{
//put your code here
}
instead of
Page_Load()
{
//code
}
I had the same problem and the solution above of "CausesValidation="False"" and even adding "UseSubmitBehavior="False"" DID NOT work - it still called "Page_Load" method.
What worked for me was adding the following line up front in Page_Load method.
if (IsPostBack) return;
I am mentioning this if it helps someone (I meant to comment above but StackOverflow did not allow me to comment because I am a new user - hence a new reply).
Try adding this to the buttons properties in the aspx page.
OnClientClick="return false;"
For my the #tgolisch answer worked better, maybe it's because i'm still a rookie.
I was trying to load a simple captcha in my WebForm and end up using a Reference Type in the Page_Load event and in a Button Click event (for a code snippet).
In the end i only have to edit some things and it's done:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var captchaText = generateCaptchaCode(5);
lblCaptcha.Text = captchaText;
}
}
protected void btnCheckCaptcha_Click(object sender, EventArgs e)
{
if (txtCaptchaCode.Text == lblCaptcha.Text)
lblMessage.Text = "Right input characters";
else
lblMessage.Text = "Error wrong characters";
}
form1.Action = Request.RawUrl;
Write this code on page load then page is not post back on button click

DotNetNuke CustomValidator strange behavior

I have a strange problem with a dotnetnuke module I'm developing.
I want to use a asp custom validator to validate some input. To keep it simple I'll check only if the field was not empty and at least a few characters long. (I know there are other standard validators that I can use).
The problem is that my code works ok locally (development), but not on production.
The only difference I know is that I use DNN 6 instead of DNN 5.
No matter what I type in on production site, it always shows me the validation error message.
These are the relevant parts of the webpage:
ASCX:
<div>
<asp:UpdatePanel ID="UpdatePanelValidationSummaryHome" ChildrenAsTriggers="False" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:ValidationSummary ID="ValidationSummary1" CssClass="validationSummary" runat="server"
EnableClientScript="False" ShowSummary="true" ShowMessageBox="false" />
<asp:CustomValidator ID="CustomValidatorActiveTab" runat="server" Display="None"
ErrorMessage="Error the field ... was not correct..." OnServerValidate="CustomValidatorActiveTab_ServerValidate"></asp:CustomValidator>
<asp:Button ID="btnZoeken" CssClass="btnZoeken" CausesValidation="true" runat="server" Text="<%$ Resources:GLOBAL, btnZoeken %>"
OnClick="btnZoeken_Click" />
Code behind
private bool ValidateTab_Ondernemingsnummer()
{
if (!String.IsNullOrEmpty(txtOndernemingsnummer.Text) && txtOndernemingsnummer.Text.Length >= 3)
{
return true;
}
return false;
}
protected void CustomValidatorActiveTab_ServerValidate(object source, ServerValidateEventArgs e)
{
int activeTab = GetActiveIndexAccordion();
switch (activeTab)
{
//Zoeken op ondernemingsnummer
case 0:
if (!ValidateTab_Ondernemingsnummer())
{
e.IsValid = false;
}
else
{
e.IsValid = true;
}
break;
}
Thanks for any help.
Any ideas?
SOLVED:
I used dotnetnuke logging to see when and why e.isValid is set to false.
My custom validator control was being called twice!!
The first time it was validated ok, the second time it was not.
My solution was to disable custom server validator control in the markup and enable it just after doing the submit (and don't forget to turn it off).
Like this:
<asp:UpdatePanel ID="UpdatePanelValidationSummaryHome" ChildrenAsTriggers="False"
UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:ValidationSummary ID="ValidationSummary1" CssClass="validationSummary" runat="server"
EnableClientScript="False" ShowSummary="true" ShowMessageBox="false" />
<asp:CustomValidator ID="CustomValidatorActiveTab" runat="server" Display="None"
EnableClientScript="false" Enabled="false" ErrorMessage="ERROR ONDERNEMINGSNUMMER"
OnServerValidate="CustomValidatorActiveTab_ServerValidate"></asp:CustomValidator>
Enabled = false is important here!
Then in the button click
protected void btnZoeken_Click(object sender, EventArgs e)
{
CustomValidatorActiveTab.Enabled = true;
CustomValidatorActiveTab.Validate();
if (Page.IsValid)
{
CustomValidatorActiveTab.Enabled = false;
I still don't know why the CustomValidatorActiveTab_ServerValidate was being called twice.
It has something to do with DNN 5 I suppose (and maybe it was fixed in DNN 6).
I hope this helped someone.
The reason the validator is called twice is due to the link button.
Generating the GridView onBubbleEvent, which also causes the validator to validate.

Pass username & password to an invisible Login Control to validate?

In my master page, on the menu there is an icon which uses Jquery to slide, showing 2 textboxes (username, password) for users to enter & 1 submit button. My idea is that after submitting, I get values of these 2 fields to assigned it to an invisible Login Control in my MasterPage, then validate automatically.
I could get values and assign but problem is I don't know how to trigger the Login button in Login Control (how to force it to process information)? the DataBind() func doesn't work
Master.master
<div id="login">
<p>
<asp:Login ID="Login2" runat="server" DestinationPageUrl="~/Index.aspx" LoginButtonStyle-CssClass="button_login"
TextBoxStyle-CssClass="input-name" Visible="false">
</asp:Login>
<asp:TextBox ID="inputUser" CssClass="input-name" Text="Username" runat="server"></asp:TextBox>
<asp:TextBox ID="inputPassword" CssClass="input-pass" Text="Password" runat="server"
TextMode="Password"></asp:TextBox>
<asp:Button ID="btn_login" CssClass="button_login" runat="server" OnClick="triggerLogin" />
</p>
</div>
Main.master.cs:
protected void triggerLogin(object sender, EventArgs e)
{
Login2.UserNameLabelText = inputUser.Text;
Login2.PasswordLabelText = inputPassword.Text;
Login2.DataBind();
}
Actually I already have a login page which processes individually, is it possible to pass information to that page to process?
You can add your username and password int o a session.
Something like:
Session["user"] = inputUser.Text;
Session["pass"] = inputPassword.Text;
By using that you can access the username,password in your pages.
var myusername = Session["user"].ToString();
var mypassword= Session["pass"].ToString();
Check this on MSDN:
ASP.NET State Management Overview
How to: Pass Values Between ASP.NET Web Pages
Regards
Yeah, I've found out the solution, without having to use Login Control. I can do it manually.
<asp:TextBox ID="inputUser" CssClass="input-name" Text="Username" runat="server"></asp:TextBox>
<asp:TextBox ID="inputPassword" CssClass="input-pass" Text="Password" runat="server"
TextMode="Password"></asp:TextBox>
<asp:Button ID="btn_login" CssClass="button_login" runat="server" OnClick="triggerLogin" />
Codebehind:
protected void triggerLogin(object sender, EventArgs e)
{
TextBox txtbxInputUser = (TextBox)Page.Master.FindControl("inputUser");
TextBox txtbxInputPass = (TextBox)Page.Master.FindControl("inputPassword");
Label samplelabel1 = (Label)Page.Master.FindControl("sampleLabel1");
if (System.Web.Security.Membership.ValidateUser(txtbxInputUser.Text, txtbxInputPass.Text))
{
System.Web.Security.FormsAuthentication.SetAuthCookie(txtbxInputUser.Text, false);
}
else
{
Response.Redirect("Login.aspx?Attempt=wrong");
}
}

No error message displayed for custom validator

I have a requirement that one of multiple fields is required. Using custom validator the even fires, false is returned, but no error message is display and the form validates.
What am I missing? I have tried with and without ValidationSummary.
Thanks!
<asp:CustomValidator ID="CustomValidator1" OnServerValidate="validatePhone" EnableClientScript="false" runat="server" ErrorMessage="Home or Cell Phone is Required" ></asp:CustomValidator>
<asp:ValidationSummary ID="ValidationSummary1" DisplayMode="BulletList" runat="server" ForeColor="Red" Font-Size="X-Small" Font-Bold="true" />
protected void validatePhone(object sender, ServerValidateEventArgs e)
{
e.IsValid = string.IsNullOrEmpty(txtCellPhone.Text) && string.IsNullOrEmpty(txtHomePhone.Text) ? false : true;
}
You have to set the ControlToValidate to some TextBox.
<asp:CustomValidator ID="CustomValidator1" OnServerValidate="validatePhone" EnabEnableClientScript="false" runat="server" ErrorMessage="Home or Cell Phone is Required" ControlToValidate="txtHomePhone"/>
Check out this article. Basically you need to wire up the client side validation.
Add the following just before the closing form tag changing the control names as needed:
<%-- This configures the validator to automatically--%>
<%-- update when either of these controls is changed --%>
<script type="text/javascript">
<!--
ValidatorHookupControlID("<%= MyControl1.ClientID %>",
document.getElementById["<%= CustomValidator1.ClientID %>"]);
ValidatorHookupControlID("<%= MyControl2.ClientID %>",
document.getElementById["<%= CustomValidator1.ClientID %>"]);
//-->
</script>
Alternatively use this control
Issue was completely my fault. On my submit button the final thing I do is a Response.Redirect. The message was coming up, but then the Thank you page was being presented. Now only doing the Response.Redirect if the customvalidator returns true.

Enable/disable RequiredValidator on client-side / CustomValidator not firing

I've got a drop-down where the user selects a Country. It is a required "field".
Next to it, there is a textfield named State. If the user selects US, then the field State is required. If the user selects e.g. Sweden, the State is not required, since Sweden has no states.
Example code:
<asp:DropDownList runat="server" ID="Country"></asp:DropDownList>
<asp:RequiredFieldValidator ControlToValidate="Country"
runat="server" Display="Static" ErrorMessage="Required field" />
<asp:TextBox runat="server" ID="State"></asp:TextBox>
<asp:CustomValidator ClientValidationFunction="DoesntGetFiredIfStateIsEmpty"
runat="server" Display="Static" ErrorMessage="Required field" />
<!-- SO, RATHER THIS TOGETHER WITH CONDITIONAL FIRING -->
<asp:RequiredFieldValidator ControlToValidate="State"
runat="server" Display="Static" ErrorMessage="Required field" />
My question to you is: How can I make this CustomValidator fire validation when it is empty?
Or put simplier: How can I make a RequiredValidator fire conditionally?
Or simplest: How can I enable/disable a RequiredValidator on client-side?
Try doing this with javascript to enable and disable validators
ValidatorEnable(RequiredFieldValidatorId, false);
Check out this question that I answered.
Asp.net has a client side javascript function to manage the validators, the "ValidatorEnable" function,
ValidatorEnable(RequiredFieldValidatorId, false);
you can call it simply using javascript, you must send the validator object to the function (not only its id).
if (x==y) {
ValidatorEnable($('#<%=rfvFamily.ClientID %>'), false);
} else {
ValidatorEnable($('#<%=rfvFamily.ClientID %>'), true);
}
or
if (x==y) {
ValidatorEnable(document.getElementById("<%=rfvFamily.ClientID %>", false);
} else {
ValidatorEnable(document.getElementById("<%=rfvFamily.ClientID %>", true);
}
full documnet on:
http://msdn.microsoft.com/en-us/library/Aa479045#aspplusvalid_clientside
another way is to Set in your DropDownList CausesValidation="false" to avoid that the validators block a postback when you change the DropDownList entry.
(*) Remember this function is for client side, for disabling validator in server side, you must to disable validator on page postback too.
if (IsPostBack){
if (x==y) {
rfvFamily.Enabled = false;
}
}

Resources