Password custom validation ain't working - c#

I have a form for registration.
I'm checking if the password has 6 characters like this :
<input type="password" runat="server" name="password" size="41" maxlength="64" id="txtpassword" /><span>*</span>
<asp:RequiredFieldValidator ID="RequiredFieldValidator8" runat="server" ErrorMessage="Fill in a password." ControlToValidate="txtpassword"></asp:RequiredFieldValidator>
<asp:CustomValidator ID="CustomValidator1" runat="server" OnServerValidate="valPassword" ErrorMessage="Password must be 6 characters long." ControlToValidate="txtpassword"></asp:CustomValidator> (at least 6 characters)
codebehind
protected void valPassword(object source, ServerValidateEventArgs args)
{
args.IsValid = ValidatePassword(args.Value);
}
private bool ValidatePassword(string pw)
{
if (pw.Length >= 6)
{
return true;
}
else
{
return false;
}
}
If I leave the RequiredFieldValidator and the CustomValidator work together and I fill in 1 character , the form is accepted.
If I delete the RequiredFiekdValidator and fill in the form, the form is accepted with no character at all in the passwordfield
If I leave the CustomValidator and I fill in 1 character , the form is accepted
My CustomValidator isn't working properly, what am I missing ?

try changing txtpassword to an <asp:Textbox> instead of an input.

maybe a problem with name vs id? I usually try to have the name and the id of an element match to avoid confusion.

Related

ASPX validation controllers not displaying messages

So this is what i have
protected void submitEmail_Click(object sender, EventArgs e)
{
try
{
if (!Page.IsValid)
{
validationMsg.Visible = true;
validationMsg.Text = "Please insert a valid email address.";
return;
}
if (!IsValidEmail())
{
validationMsg.Visible = true;
validationMsg.Text = "Please insert a valid email address.";
return;
}
SaveData();
validationMsg.Visible = true;
validationMsg.Text = "Thank you for joining our beta community! We’ll send word as soon as our beta is out.";
}
catch (Exception ex)
{
}
}
And a .aspx :
<%# Control Language="C#"
AutoEventWireup="true"
CodeFile="BetaEmailUserForm.ascx.cs"
Inherits="CMSWebParts_BullGuard_User_Forms_BetaEmailUserForm" %>
<div class="subscribe">
<asp:TextBox ID="userEmail" runat="server"
CssClass="subscribe-input"></asp:TextBox>
<asp:LinkButton ID="submitEmail" runat="server"
OnClick="submitEmail_Click"
CssClass="subscribe-submit button"
CausesValidation="true"
ValidationGroup="betaEmailGroup">
<span style="font-size: 20px; color: #ffffff;padding: 26px;display:block;">✓</span>
</asp:LinkButton>
</div>
<p class="thank">
<asp:Literal ID="validationMsg"
runat="server"
Visible="false"></asp:Literal>
<asp:RequiredFieldValidator ID="rfvEmail1new"
ControlToValidate="userEmail"
SetFocusOnError="true"
EnableClientScript="true"
ValidationGroup="betaEmailGroup"
runat="server"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revEmail1new"
ControlToValidate="userEmail"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"
SetFocusOnError="true"
EnableClientScript="true"
ValidationGroup="betaEmailGroup"
runat="server"></asp:RegularExpressionValidator>
</p>
What i want is this.
case 1 : i enter nothing in the input filed the 1st validator takes action and in the .cs file i assume that the 1st condition should fail, resulting in adding the message
case 2 : i enter an invalid email address => same logic as for case 1
case 3 : enter a good email address skip the 2 checks
case 4 : enter an already registered email address ==> go to 2nd check condition.
The issue is that i don't get the messages displayed for the 2 Validators.
1st case I don't enter any data i want to go with the following case
if (!Page.IsValid)
It does not happen.
2nd case that fails is if the email address is not correct (eg. asdasd#dadad)
should also go with the case where page is not valid
if (!Page.IsValid)
I've tried to debug butcouldn't debug for the 1st and 2nd test cases.
I can debug only if i enter a valid email address.
Any help? thank you.
I'm thinking that there are some client side validation that the aspx controllers will do for me in the back without my knowledge, some js generated files? don't know
I wish the problem is for "!Page.IsValid".
Look at the following links
https://msdn.microsoft.com/en-us/library/system.web.ui.page.isvalid(v=vs.110).aspx
How does Page.IsValid work?
Sometimes need to add " ErrorMessage="" " to the validations tag. Please also check it.
I wish this will help you.
There is also others easy way to do this job which is build in, you can follow them.

asp.net Textbox Textmode Number, allow numbers only

I would just like to know if there is a way in ASP.NET to allow only numbers in textboxes with textmode="number"
when I use this:
<asp:TextBox runat="server" TextMode="Number" ID="TextBoxDuration" Width="250"></asp:TextBox>
<asp:RequiredFieldValidator ControlToValidate="TextBoxDuration" runat="server" ErrorMessage="Dieses Feld darf nicht leer sein" /><br />
<asp:RegularExpressionValidator runat="server" ControlToValidate="TextBoxDuration" validationexpression="((\d+)((\.\d{1})?))$" ErrorMessage="Nur Zahlen" />
users can still input the char e and +, -
I don't like to use normal Textbox with the same Regularexpressionvalidator (which actually would work)
example:
You can simply use regular expression validator as
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
ControlToValidate="TextBox1" runat="server"
ErrorMessage="Only Numbers allowed"
ValidationExpression="\d+">
</asp:RegularExpressionValidator>
Also you can use the below regular expression to make the text-field as 12 digit number to be added.(madatory)
^[0-9]{12}$
Also you can make the field as between 10 and 12 digits (mandatory) as below
^[0-9]{10-12}$
You can use RegularExpressionValidator for this. below is the sample code:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ControlToValidate="TextBox1" runat="server" ErrorMessage="Only Numbers allowed" ValidationExpression="\d+"></asp:RegularExpressionValidator>
above TextBox only allowed integer to be entered because in RegularExpressionValidator has field called ValidationExpression, which validate the TextBox. However, you can modify as per your requirement.
You can see more example in MVC and Jquery here.
You can use jQuery like this
Number : <input type="text" name="quantity" id="quantity" /> <span id="errmsg"></span>
<script>
$(document).ready(function () {
//called when key is pressed in textbox
$("#quantity").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
});
</script>
you can make a Javascript function into your Textbox.
Try <asp:TextBox ID="txtNumero" Text="" onkeydown="return jsDecimals(event);" Width="75px" runat="server"></asp:TextBox>
Then
function jsDecimals(e) {
var evt = (e) ? e : window.event;
var key = (evt.keyCode) ? evt.keyCode : evt.which;
if (key != null) {
key = parseInt(key, 10);
if ((key < 48 || key > 57) && (key < 96 || key > 105)) {
//Here is where respond with 0 o 1.
if (!jsIsUserFriendlyChar(key, "Decimals")) {
return false;
}
}
else {
if (evt.shiftKey) {
return false;
}
}
}
return true;
}
REGEX
^[0-9]*$
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="tbAccount"
ErrorMessage="Please Enter Only Numbers" ForeColor="Red" ValidationExpression="^\d+$"> </asp:RegularExpressionValidator>
IF YOU DON'T WANT USER TO TYPE OTHER CHARACTER ON KEY EVENT THEN
$('#TEXTBOXID').keypress(function (e) {
var a = [];
var k = e.which;
for (i = 48; i < 58; i++)
a.push(i);
// allow a max of 1 decimal point to be entered
if (!(a.indexOf(k) >= 0)) e.preventDefault();
});
you can use filter textbox extender.
it will allows only number.
there is no negative numbers or e,+,- keys
<asp:FilteredTextBoxExtender ID="TextBox1_FilteredTextBoxExtender" runat="server" Enabled="True" TargetControlID="txtDay" FilterType="Numbers"> </asp:FilteredTextBoxExtender>
You can also use asp.net field validate like this
<asp:TextBox runat="server" CssClass="form-control" ID="txtNumero" />
<asp:RegularExpressionValidator
ID="txtNumero"
ControlToValidate="EmailTextBox"
Text="(Invalid number)"
ForeColor="Red"
ValidationExpression="^\d+$"
runat="server" />
In the code-behind, just set
this.TextBoxDuration.Attributes["type"] = "number";
Adding Type="number" will work.
<asp:TextBox ID="txtQty" type="number" runat="server"></asp:TextBox>

Custom Validation doesn't fire

Here are my lines of code:
For the Textbox and the CustomValidator:
<asp:TextBox ID="Edit_Tbox_Email" runat="server" placeholder="Email Address..." CausesValidation="true" ValidationGroup="submission"></asp:TextBox>
<asp:CustomValidator runat="server" ControlToValidate="Edit_Tbox_Email" ID="cv_Email" OnServerValidate="cv_Email_ServerValidate" ErrorMessage="!" data-toggle="tooltip" title="Invalid Input!" ValidationGroup="submission"></asp:CustomValidator>
This is for the Button to allow the user to change his/her email:
<asp:Button ID="Edit_But_Email" runat="server" Text="Change" CssClass="btn btn-small" OnClick="Edit_But_Email_Click" ValidationGroup="submission" CausesValidation="true"/>
On server side:
protected void Edit_But_Email_Click(object sender, EventArgs e)
{
if(Page.IsValid)
Edit_Lab_Email.Text = Edit_Tbox_Email.Text;
}
protected void cv_Email_ServerValidate(object source, ServerValidateEventArgs args)
{
string emailRegex = "^\\w+[\\w-\\.]*\\#\\w+((-\\w+)|(\\w*))\\.[a-z]{2,3}$";
if (Edit_Tbox_Email.Text.Length == 0 || Regex.IsMatch(Edit_Tbox_Email.Text, emailRegex))
{
cv_Email.IsValid = false;
}
}
But the problem here is that cv_Email_ServerValidate() doesn't even fire. Basically, it doesn't validate the Textbox. Also, I don't want to use the RequiredFieldValidator and RegularExpressionValidator. I want to combine their functionalities into just one validator. And as much as possible I would like to use the code behind(c#) only and not by jQuery. Thank You!
Your button have a ValidationGroup but your CustomValidator don't have one. If you want your button to valide it, you must set the same ValidationGroup.
Edit:
You have to set ValidateEmptyText="true" otherwise, it won't validate empty value.

Validating textbox only if checkbox is checked - no post back

I have a asp.net CheckBox and I have a textbox, I only want textbox to validate when checkbox is checked otherwise just leave it like this.
I find MVC post but I want for asp.net forms Validating textbox only if checkbox is checked using MVC
This is my current code which validates textbox regardless of checkbox is checked or not,
<asp:TextBox ID="txtSubject" runat="server" />
<asp:CheckBox ID="chkSubjectRequired" runat="server" />
<asp:RequiredFieldValidator ID="rfvSubject" ControlToValidate="txtSubject" ErrorMessage="You must enter a subject." runat="server" />
You will need a custom validator ,then:
<asp:TextBox ID="txtSubject" runat="server" />
<asp:CustomValidator ControlToValidate="txtSubject" OnServerValidate="IsTextboxValid" Text="Text box is invalid" runat="server"/>
In code behind,define custom validation method:
protected void IsTextboxValid(object sender,ServerValidateEventArgs e)
{
e.IsValid=chkSubjectRequired.Checked;
}
Please note that this is Server-side Validation
this is what you looking for. Just enable/disable the validator (also textbox if you want) that's all.
Validate The Text Box Only Number :
<input type="text" onkeydown="ValidateNumber(event);">
<script>
function ValidateNumber(e) {
if ((e.keyCode >= 8 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105)) {
return true
}
return false;
};

Responding to an "enter" keypress within an <input> field

My question is about handling Enter key press.I have one page called "order.aspx" which is residing inside master page.Here i am explaining the control structure
1. <asp:TextBox ID="txtSearch" MaxLength="50" runat="server" Width="420px" CssClass="txtbox"></asp:TextBox>
2. <asp:Button ID="btnSearch" runat="server" OnClick="btnSearch_Click" />
3. one asp grid control with one column containing textbox for entering order quantity
4. <asp:Button ID="btnOrder" runat="server" OnClick="btnOrder_Click" />.
My requirement is,
while user enter text in the search textbox and press enter key then btnSearch_Click should fire
while user enter quantity in the grid textbox and press enter key then btnOrder_Click should fire.
I tried with different code finally got answers but it is not fully functional.Follwing is the javascript code i have used.
function DoEnterKeyButtonClick(buttonId) {
e = event;
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
document.getElementById('ctl00_CphMaster_' + buttonId).click();
return false;
}
}
I am calling this method on key press of txtSearch and grid textbox and passing the Button id to fire event btnSearch and btnOrder respectively.When i am entering the text in the search textbox and hitting the enter key then btnSearch_Click is firing and when i am entering the order quantity and hitting the enter key the btnOrder_Click is firing.But the issue is,after changing the page index say second page the required functionality not working.That is when i am entering order quantity and hitting the enter key then btnSearch_Click will fire first , then btnOrder_Click firing.This will clear the quantity entered and results in error.Please help me...
Thanks,
Joby
Instead of giving this document.getElementById('ctl00_CphMaster_' + btnSearch).click();
Try this document.getElementById('<%= btnSearch.ClientID %>').click();
or try using jquery
$("#txtSearch").keyup(function(event){
if(event.keyCode == 13){
$("#btnSearch").click();
}
});
Else place your controls inside the asp:panel and set the DefaultButton property as btnSearch as like below
<asp:Panel ID="Panel1" runat="server" DefaultButton="btnSearch">
<asp:TextBox ID="txtSearch" MaxLength="50" runat="server" Width="420px" CssClass="txtbox"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" OnClick="btnSearch_Click" />
</asp:Panel>
Hope this will help.
Many Thanks
Anna
Your function doesn't know what exactly this even is.
Try it like this
function DoEnterKeyButtonClick(event,buttonId){}
I keep the following handy snippet around..
function getIntKey(key) {
var keycode;
if (key == null) { keycode = event.keyCode; } else { keycode = key.keyCode; }
return keycode;
}
And use it, like this..
$("#txtSearch").keyup(function(e){
if(getIntKey(e) == 13){
//Enter was pressed, do somthing
}
});

Categories