The following code is used to validate when form submit button is hit, but I am not getting the wanted result back.
It should display the error messages but they are not being displayed what am I doing wrong?
The custom validator validates passwords, it should change the error message based on the which errors occur:
Password is blank
Password is invalid
Passwords do not match
Only one error should show at a time so I wrote this custom validtor in .ascx.cs:
protected void cvPasswordValidation_ServerValidate(object source, ServerValidateEventArgs args)
{
bool IsPasswordBlank = false;
bool IsPasswordValid = false;
cvPasswordValidation.IsValid = false;
// If password is blank then IsValid is false, show blank password errors.
if (String.IsNullOrEmpty(args.Value))
{
//args.IsValid = false;
IsPasswordBlank = true;
//Show blank password error depending on which box is empty.
if (String.IsNullOrEmpty(txtPassword.Text))
{
cvPasswordValidation.ErrorMessage = "You must enter password";
}
else
{
cvPasswordValidation.ErrorMessage = "You must confirm password";
}
cvPasswordValidation.IsValid = false;
}
else
{
cvPasswordValidation.IsValid = true;
}
// If password is not valid format then IsValid is false, show invalid format errors.
if (!Regex.IsMatch(args.Value, RegexHelper.ValidPassword))
{
IsPasswordValid = true;
//Show invalid format errors, if password is not blank
if (IsPasswordBlank == false)
{
cvPasswordValidation.ErrorMessage = "<b>Current password</b> not in correct format. Your password must contain 6 - 12 characters with a combination of numbers and letters.";
}
cvPasswordValidation.IsValid = false;
}
else
{
cvPasswordValidation.IsValid = true;
}
// If passwords do not match then IsValid is false, show do not match errors.
bool areEqual = String.Equals(txtPassword.Text, txtConfirmPassword.Text, StringComparison.Ordinal);
if (areEqual == false)
{
//Show do not match errors is password is not blank and is not invalid format
if (IsPasswordBlank == false && IsPasswordValid == false)
{
cvPasswordValidation.ErrorMessage = "Your passwords do not match.";
}
cvPasswordValidation.IsValid = false;
}
else
{
cvPasswordValidation.IsValid = true;
}
}
and the .ascx:
<asp:TextBox runat="server" ID="txtPassword" MaxLength="12" autocomplete="off" TextMode="Password" ValidationGroup="vgOnlineDetails"></asp:TextBox>
<asp:CustomValidator ID="cvPasswordValidation"
runat="server"
display="Dynamic"
OnServerValidate="cvPasswordValidation_ServerValidate"
ControlToValidate="txtPassword"
ValidationGroup="vgOnlineDetails">
</asp:CustomValidator>
You need to set ValidateEmptyText = true to validate empty fields.
You shoul use return after assignment to IsValid property. Condider situation when you do not specify password at all. If you do not specify return after assignment all three if statements will be executed. In last if areEqual variable will be true because two empty strings are equal and cvPasswordValidation.IsValid = true; will be executed. In this case your text boxes will be valid.
Related
<asp:FileUpload ID="FUpImg1" runat="server" CssClass="control-label" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="FUpImg1" ValidationExpression="(.*?)\.(jpg|png|JPG|PNG)$"
CssClass="text-danger" ErrorMessage="Please Upload .jpg, .png only" Display="Dynamic"></asp:RegularExpressionValidator>
its not working its directly going on server side not validate my image extension. what is wrong with above code?
Thanks in advance!
RegularExpressionValidator only validate when i upload anything in the FileUploader!
that why its not validate anything when its null and going on server side in my question.
i use customvalidator with js function because i have 5 different FileUploader and i have to pass same function.
function validateImageExtension(source, args) {
var reg = /^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.jpg|.png|.jpeg)$/;
if (args.Value == "" || args.valueOf == null) {
args.IsValid = false;
source.innerText = "Image is Required*";
}
else {
//Checks with the control value.
if (reg.test(args.Value)) {
args.IsValid = true;
source.innerText = "";
}
else {
//If the condition not satisfied shows error message.
args.IsValid = false;
source.innerText = "Only .jpg, .png, .jpeg files are allowed!";
}
}
}
idk how it work btw. i just copy paste it from 5 different blogs.
I am creating a multi form application which has a series of validation test before the user can save the form. One of those validation functions needs evaluate if the user has entered certain keywords, such as 'Unkown', 'TBA', 'N/A'.I need to begin by normalizing the input string, to strip all unwanted characters such as Whitespace, and extra casing such as 'UNkown', 'tBA'. This then needs to be checked against my list.
This is my current method however my regex doesn't normalize my input string correctly and will pass validation if there is a space in-front of the word
public bool useUnkownEntity(string strTest)
{
Regex rgx = new Regex(#"^[a-zA-Z]");
List<string> unkown = new List<string> { "Unkown", "tba", "tbc","N/a"};
useUnkownEntity(rgx.Replace(strTest, ""));
if (unkown.Contains(strTest, StringComparer.OrdinalIgnoreCase))
{
MessageBox.Show("please refre to the unkown ENtity within");
return false;
}
return true;
}
My desired result be false if any of the desired words are found iregardless if they are not a exact match. What would be the best approach, to capture all possibilities a user may enter to get passed validation.
This is the event I am calling the method from
private void txt_SurName_Validating(object sender, CancelEventArgs e)
{ // Convert User input to TitleCase
if (useUnkownEntity(txt_SurName.Text))
{
return;
}
if (string.IsNullOrWhiteSpace(txt_SurName.Text))
{
epSurname.Clear(); _IsValid = true;
}
else if (util.IsAllLetters(txt_SurName.Text))
{
epSurname.Clear(); txt_SurName.Text = util.ToTitle(txt_SurName.Text); _IsValid = true;
}
else
{
epSurname.SetError(txt_SurName, "InValid Surname"); _IsValid = false;
}
}
This is my answer so far, it ignores casing but not spacing, if I enter a few spaces at the beginning of the word it will fail, just as it will if a / is forgotten on N/A.
public bool useUnkownEntity(string strTest)
{
Regex rgx = new Regex("[^a-zA-Z/s/ ]");
List<string> unkown = new List<string> { "Unkown", "tba", "tbc","N/A"};
strTest = rgx.Replace(strTest, "");
if (unkown.Contains(strTest, StringComparer.OrdinalIgnoreCase))
{
MessageBox.Show("Please refer to the unkown Entity within!!");
return false;
}
return true;
}
Here is my login script. I have two users 20002143, and 60000027 the first will authenticate and redirect as scripted the second will authenticate and stay on the same page. I cannot figure out why. I have inserted breakpoints all over this code and it tells me it authenticates but then why is the login page just reloading:
public bool AuthenticateActiveDirectory(string Domain, string EmployeeID, string Password)
{
try
{
DirectoryEntry entry = new DirectoryEntry("LDAP://" + Domain, EmployeeID, Password);
object nativeObject = entry.NativeObject;
return true;
}
catch
{
return false;
}
}
protected void btnLogin_Click(object sender, EventArgs e)
{
string Domain = "domain.local";
string EmployeeID = txtUserID.Text;
string Password = txtPassword.Text;
string ADStatus = null;
if (AuthenticateActiveDirectory(Domain, EmployeeID, Password) == true)
{
ADStatus = "Success";
Session["SessionLoginStatus"] = ADStatus;
Response.Redirect("Intro.aspx?redir=Success&userid=" + EmployeeID);
}
else
{
ADStatus = "Failure";
Session["SessionLoginStatus"] = ADStatus;
lblADError.Visible = true;
lblADError.Text = "Please Check Your Password<br />";
}
}
Here is the other part of this. If I use the URL to login falsely with the second empID
https://www.site.com/folder/intro.aspx?redir=Success&userid=60000027
it will redirect me back to the login but this makes no sense also since Intro.aspx login check is scripted like this.
//checking to see if user logged in
if ((ADStatus == "Success") && (UserID.Length >= 8))
{
}
if ((ADStatus == null) || (UserID.Length < 8))
{
ADStatus = "Failure";
Session["SessionLoginStatus"] = ADStatus;
Response.Redirect("https://www.site.com/folder/userlogin.aspx");
}
else if (ADStatus == "Failure")
{
ADStatus = "Failure";
Session["SessionLoginStatus"] = ADStatus;
Response.Redirect("https://www.site.com/folder/userlogin.aspx");
}
What am I leaving out or doing wrong here?
Edited
The issue was caused by logic on the second page which tossed the user back to the login if the user's ID did not match a list of users defined in a SQL table.
In no way, shape or forum are you authenticating users on LDAP server. In fact, your authentication method will never return false because entry will never be null and the constructor for DirectoryEntry will never throw an exception.
With that being said, check that you're typing in the credentials correctly (because I know you're not). Look at your in statement for the redirect. Since your authenticate method always returns true, it will try to redirect every and anyone however fail because you're using invalid credentials.
So, how about you actually authenticate users using PrincipalContext. Here is a little explaining between the two with this DirectoryEntry question.
By the way, you're going to want to use the bool returned by PrincipalContext.ValidateUser call.
How do I ensure that the user of my web form application has entered an email address? I have seen examples using regex and the EmailAddress(), but how can I implement one or the other in the if else statement below?
if (emailTextBox.Text == "" || emailTextBox.Text.Length > 100)
{
emailErrorString = "Email: Enter email address. No more than 100 characters.\n\n";
emailString = null;
errorMessage = true;
}
else
{
emailString = emailTextBox.Text;
emailErrorString = null;
}
I tried the following code and it came back true even when I entered an invalid email address "jj#jj. I did not enter ".com, or ,net, or anything like that:
if (emailTextBox.Text == "" || emailTextBox.Text.Length > 100 ||
IsValid(emailTextBox.Text).Equals(false))
{
emailErrorString = "Email: Enter a valid email address. No more than 100
characters.\n\n"; emailString = null; errorMessage = true;
}
else
{
emailString = emailTextBox.Text; emailErrorString = null;
}
You can make use of MailAddress class, like below:
public bool IsValid(string emailAddress)
{
try
{
MailAddress m = new MailAddress(emailaddress);
return true;
}
catch (FormatException)
{
return false;
}
}
Alternatively,
you can use RegEx (you should be able to find one suitable for validating email address).
This link gives a basic idea of available characters/patterns: Regexlib
I tried using the MailAddress() example and "jj#jj" came back as a valid email. So, I tried the following and it worked perfectly:
///Create a Regular Expression
Regex regEmail = new Regex(#"^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?
\^_`{|}~]+)*"
+ "#"
+ #"((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$");
And:
///test the email textbox against the created Regular Expression
if (emailTextBox.Text == "" || emailTextBox.Text.Length > 100 ||
!regEmail.IsMatch(emailTextBox.Text))
{
emailErrorString = "Email: Enter a valid email address. No more than
100 characters.\n\n";
emailString = null;
errorMessage = true;
}
else
{
emailString = emailTextBox.Text;
emailErrorString = null;
}
Well, if it could be any kind of e-mail adress, and the code doesn't have to check whether it's valid or not, you could use this code, which is based on this structure:
example#domain.extension
The only thing is to check whether the string contains an # character, a . character, and a valid e-mail domain and extension (com/de/org/...).
public bool CheckAdress(string Adress)
{
if (Adress.IndexOf('#') == -1)//if there are no # characters in the Adress
{
return false;
}
switch (Adress.Substring(Adress.IndexOf('#') + 1, Adress.IndexOf('.') - Adress.IndexOf('#') + 1)//examines the domain between the # and the. characters
{
case "gmail":
case "freemail":
case "citromail":
//... (any valid domain name)
break;
default:
return false;
}
switch (Adress.Substring(Adress.IndexOf('.') + 1, Adress.Length - Adress.IndexOf('.') + 1))//finally examines the extension
{
case "com":
case "de":
case "org":
//... (any valid extension)
break;
default:
return false;
}
//if all of these have not returned false, the adress might be valid, so
return true;
}
This code only works when there's nothing else in the TextBox, just the adress in question.
I know this is a bit long and maybe not the most perfect answer. But this way you can customize, which domains and extensions are accepted by the code, and which are not.
But if you want to check if this e-mail adress exists in reality, I don't think this solution works.
I didn't add the code that throws exception when the length is more than 100, but you can add it anytime.
Hope this helps a bit! :)
Try creating a new System.Net.Mail.MailAddress object. Pass in the Text property of the TextBox you are using for user input as the parameter to this constructor. Wrap this in a Try Catch block. You'll get a FormatException if the address is invalid.
How to validate a mobile number textbox and email textbox using regular expressions in C#?
I want to validate these first at the front end itself so that the database doesn't receive any invalid input or rather even checks for it.
I am using Windows Forms.
You can use System.Text.RegularExpression
I'll give you an example for e-mail validation
then declare a regular expression like
Regex myRegularExpression = new
Regex(" \b[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b");
and say your e-mail textbox is txtEmail
then write,
if(myRegularExpression.isMatch(txtEmail.Text))
{
//valid e-mail
}
Update
Not an expert on regular expressions,
Here's the link to Regular expression to validate e-mail
you can find more details about the regEx from the link provided.
//for email validation
System.Text.RegularExpressions.Regex rEMail = new System.Text.RegularExpressions.Regex(#"^[a-zA-Z][\w\.-]{2,28}[a-zA-Z0-9]#[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$");
if (txt_email.Text.Length > 0)
{
if (!rEMail.IsMatch(txt_email.Text))
{
MessageBox.Show("E-Mail expected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
txt_email.SelectAll();
e.Cancel = true;
}
}
//for mobile validation
Regex re = new Regex("^9[0-9]{9}");
if (re.IsMatch(txt_mobile.Text.Trim()) == false || txt_mobile.Text.Length > 10)
{
MessageBox.Show("Invalid Indian Mobile Number !!");
txt_mobile.Focus();
}
This code will check whether an email address is valid:
string inputText = textBox1.Text;
if (Regex.IsMatch(inputText,
#"^(?("")("".+?""#)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])#))" +
#"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$"))
{
MessageBox.Show("yes");
}
else
{
MessageBox.Show("no");
}
(source: http://msdn.microsoft.com/en-us/library/01escwtf.aspx)
For phone numbers, it's not so simple - the answer depends on where in the world you are, whether you want to allow international numbers, how mobiles are numbered (for example, in the USA, you can't tell from a phone number alone whether it's a mobile number or not). Look up "Telephone numbering plan" on Wikipedia for more information.
In ASP.NET you can use a RegularExpressionValidator control.
To determine the regular expression itself, you can experiment with a tool like Expresso.
Be aware that validating emails with regular expressions is a hard task, if you want to allow all the possibly valid email formats; probably the best thing to do in that case would be to send an email to the entered address with a confirmation link, and when that link is clicked, you assume that the mail is valid.
See Email Address Validation Using Regular Expression (The Code Project) for email validation and see Best practice for parsing and validating mobile number (Stack Overflow) for mobile number validation.
I do the numeric validation this way as shown in the code below.
No need for checking char by char and user culture is respected!
namespace Your_App_Namespace
{
public static class Globals
{
public static double safeval = 0; // variable to save former value!
public static bool isPositiveNumeric(string strval, System.Globalization.NumberStyles NumberStyle)
// checking if string strval contains positive number in USER CULTURE NUMBER FORMAT!
{
double result;
boolean test;
if (strval.Contains("-")) test = false;
else test = Double.TryParse(strval, NumberStyle, System.Globalization.CultureInfo.CurrentCulture, out result);
// if (test == false) MessageBox.Show("Not positive number!");
return test;
}
public static string numstr2string(string strval, string nofdec)
// conversion from numeric string into string in USER CULTURE NUMBER FORMAT!
// call example numstr2string("12.3456", "0.00") returns "12.34"
{
string retstr = "";
if (Globals.isPositiveNumeric(strval, System.Globalization.NumberStyles.Number)) retstr = double.Parse(strval).ToString(nofdec);
else retstr = Globals.safeval.ToString(nofdec);
return retstr;
}
public static string number2string(double numval, string nofdec)
// conversion from numeric value into string in USER CULTURE NUMBER FORMAT!
// call example number2string(12.3456, "0.00") returns "12.34"
{
string retstr = "";
if (Globals.isPositiveNumeric(numval.ToString(), System.Globalization.NumberStyles.Number)) retstr = numval.ToString(nofdec);
else retstr = Globals.safeval.ToString(nofdec);
return retstr;
}
}
// Other Your_App_Namespace content
}
// This the way how to use those functions in any of your app pages
// function to call when TextBox GotFocus
private void textbox_clear(object sender, System.Windows.RoutedEventArgs e)
{
TextBox txtbox = e.OriginalSource as TextBox;
// save original value
Globals.safeval = double.Parse(txtbox.Text);
txtbox.Text = "";
}
// function to call when TextBox LostFocus
private void textbox_change(object sender, System.Windows.RoutedEventArgs e)
{
TextBox txtbox = e.OriginalSource as TextBox;
// text from textbox into sting with checking and string format
txtbox.Text = Globals.numstr2string(txtbox.Text, "0.00");
}
For Email Validation use the following Regex Expression as below in Lost Focus event of the Textbox.
Use System.Text.RegularExpression Namespace for Regex.
Regex emailExpression = new Regex(#"^[a-zA-Z][\w\.-]{2,28}[a-zA-Z0-9]#[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$");
and then check it by using below code
if (emailExpression.IsMatch(textbox.Text))
{
//Valid E-mail
}
For PhoneNumber Validation use the following code in PreviewTextInput event of the Textbox.
private void PhoneNumbeTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = !AreAllValidNumericChars(e.Text);
}
private bool AreAllValidNumericChars(string str)
{
bool ret = true;
if (str == System.Globalization.NumberFormatInfo.CurrentInfo.CurrencyDecimalSeparator |
str == System.Globalization.NumberFormatInfo.CurrentInfo.CurrencyGroupSeparator |
str == System.Globalization.NumberFormatInfo.CurrentInfo.NegativeSign |
str == System.Globalization.NumberFormatInfo.CurrentInfo.NegativeInfinitySymbol |
str == System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator |
str == System.Globalization.NumberFormatInfo.CurrentInfo.NumberGroupSeparator |
str == System.Globalization.NumberFormatInfo.CurrentInfo.PercentDecimalSeparator |
str == System.Globalization.NumberFormatInfo.CurrentInfo.PercentGroupSeparator |
str == System.Globalization.NumberFormatInfo.CurrentInfo.PerMilleSymbol |
str == System.Globalization.NumberFormatInfo.CurrentInfo.PositiveInfinitySymbol |
str == System.Globalization.NumberFormatInfo.CurrentInfo.PositiveSign)
return ret;
int l = str.Length;
for (int i = 0; i < l; i++)
{
char ch = str[i];
ret &= Char.IsDigit(ch);
}
return ret;
}