Validate Checkbox and Checkboxlist in easy way
Hi Good Evening Techies.
Validation Control for Checkbox and Checkboxlist
Alternatively Download the file here skmValidators.rar
Hi Good Evening Techies.
Hi , Now i am going to discuss about how to validate a Indian Mobile Number.
First the Mobile Number field should not be null so for that - Add RequiredFieldValidator.
It should not accept any Aplhabets , or any special characters for this you have to write RegularExpression Validator to Accept only Numbers
EX:
Regex: \d+
How to Validate the CreditCard in asp.net ??
To validate the CreditCard first you have to check the Card Type then followed by
the no.of digits..etc.. on that Specific Card type. here i am using Luhn Algorithm to validate.
So you have place these algorithm on Separate Class file ie: Create
CardValidator.cs on the App_Code Folder and paste the below code.
using System; public enum CardType { MasterCard, BankCard, Visa, AmericanExpress, Discover, DinersClub, JCB }; public sealed class CardValidator { private CardValidator() { } // static only public static bool Validate(CardType cardType, string cardNumber) { byte[] number = new byte[16]; // number to validate // Remove non-digits int len = 0; for(int i = 0; i < cardNumber.Length; i++) { if(char.IsDigit(cardNumber, i)) { if(len == 16) return false; // number has too many digits number[len++] = byte.Parse(cardNumber[i].ToString ()); } } // Validate based on card type, first if tests length, second tests prefix switch(cardType) { case CardType.MasterCard: if(len != 16) return false; if(number[0] != 5 || number[1] == 0 || number[1] > 5) return false; break; case CardType.BankCard: if(len != 16) return false; if(number[0] != 5 || number[1] != 6 || number[2] > 1) return false; break; case CardType.Visa: if(len != 16 && len != 13) return false; if(number[0] != 4) return false; break; case CardType.AmericanExpress: if(len != 15) return false; if(number[0] != 3 || (number[1] != 4 && number[1] != 7)) return false; break; case CardType.Discover: if(len != 16) return false; if(number[0] != 6 || number[1] != 0 || number[2] != 1 || number[3] != 1) return false; break; case CardType.DinersClub: if(len != 14) return false; if(number[0] != 3 || (number[1] != 0 && number[1] != 6 && number[1] != 8) || number[1] == 0 && number[2] > 5) return false; break; case CardType.JCB: if(len != 16 && len != 15) return false; if(number[0] != 3 || number[1] != 5) return false; break; } // Use Luhn Algorithm to validate int sum = 0; for(int i = len - 1; i >= 0; i--) { if(i % 2 == len % 2) { int n = number[i] * 2; sum += (n / 10) + (n % 10); } else sum += number[i]; } return (sum % 10 == 0); } }
try { bool validateCard = false; if (ddlCCType.SelectedValue.ToString() == "Visa") { validateCard = CardValidator.Validate( CardType.Visa , txtCCNumber.Text); } else if (ddlCCType.SelectedValue.ToString() == "MasterCard") { validateCard = CardValidator.Validate(CardType.MasterCard , txtCCNumber.Text); } else if (ddlCCType.SelectedValue.ToString() == "AMEX") { validateCard = CardValidator.Validate(CardType.AmericanExpress, txtCCNumber.Text); } if (validateCard != false) { string ipaddress; ipaddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (ipaddress == "" || ipaddress == null) { ipaddress = Request.ServerVariables["REMOTE_ADDR"]; } Session["ipAddress"] = ipaddress; //API Credentials (3-token) string strUsername = "troy2._1261822640_biz_api1.gmail.com"; string strPassword = "1261822646"; string strSignature = "An5ns1Kso7MWUdW4ErQKJJJ4qi4-A60C4mgCoX2-L9FhwhF2rfGtRPeI"; string strCredentials = "USER=" + strUsername + "&PWD=" + strPassword + "&SIGNATURE=" + strSignature; // For Sandbox testing use this API string strNVPSandboxServer = "https://api-3t.sandbox.paypal.com/nvp"; // Fpr Live Server use this API string strNVPLiveServer = "https://api-3t.paypal.com/nvp"; string strAPIVersion = "2.3"; // here i am assigning the credit card type cardno,expiry date/month to //the session variable and pass it here string strNVP = strCredentials + "&METHOD=DoDirectPayment&CREDITCARDTYPE=" + Session["cardType"].ToString() + "&ACCT=" + Session["cardNo"].ToString() + "&EXPDATE=" + Session["expiryDate"].ToString() + "&CVV2=808&AMT=" + Amount_Label.Text + "&FIRSTNAME=" + FirstName_Label.Text + "&LASTNAME=" + LastName_Label.Text + "&IPADDRESS=" + Session["ipAddress"].ToString() + "&STREET=" + address1 + "+" + address2 + "&CITY=" + city + "&STATE=" + state + "&COUNTRY=" + country + "&ZIP=" + zip + "&COUNTRYCODE=US&PAYMENTACTION=Sale&VERSION=" + strAPIVersion; //Create web request and web response objects, make sure you using the correct server (sandbox/live) HttpWebRequest wrWebRequest = (HttpWebRequest)WebRequest.Create(strNVPSandboxServer); ////Set WebRequest Properties wrWebRequest.Method = "POST"; //// write the form values into the request message StreamWriter requestWriter = new StreamWriter(wrWebRequest.GetRequestStream()); requestWriter.Write(strNVP); requestWriter.Close(); //// Get the response. HttpWebResponse hwrWebResponse = (HttpWebResponse)wrWebRequest.GetResponse(); StreamReader responseReader = new StreamReader(wrWebRequest.GetResponse().GetResponseStream()); //// and read the response string responseData = responseReader.ReadToEnd(); responseReader.Close(); Response.Write(Server.UrlDecode(responseData)); } else { validateCard_Label.Text = "Please check your card number..."; } } catch (Exception ex) { throw ex; }
Today , we are going to discuss about the Regular Expression for Indian Phone Numbers.
Default there is only few Regex available on .net Regularexperssion validator controls.
so if we want to validate our textbox field like indian phone numbers, landline number we have write it own Expression.
There is expression tools available to - Check the Expression is valid or not. I have no idea about this because i have not used.
To accept Indian (Landline) phone numbers check this Regex : /^[0-9]\d{2,4}-\d{6,8}$/
This is indian phone number. where it will take a format of std code 3 to 4 digits, hypen and rest of the 6 to 8 digits.
Ex: 0222-8345622 or 09786-567567
This one is for eight digit no :: \d{8} eg: 26440050
This one is for mobile no:: \d{10} eg: 9998945678
This one is for mobile no with india code \d{13} eg 9109998945678
This one is for Mobile no with india code then space and then mobile no whith zero as starting :: +\d{2}\s\d{9} eg:+91 09998945678
Now we have to discuss about the validationexpression ie:
the textbox should accept empty values , numeric ( float ) .
Implementation Code :
^\d*\.?\d*$
HTML
Matches
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator3" runat="server" ErrorMessage="Invalid format" ControlToValidate="TextBox3" ValidationExpression="^\d*\.?\d*$" ValidationGroup="d"></asp:RegularExpressionValidator>
<asp:Button ID="Button5" runat="server" Text="Button" ValidationGroup="d" />
Now we are going to discuss about the validate the decimal numbers it should be in the format of
<asp:TextBox ID="Phone_TextBox" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="RegularExpressionValidator"
ValidationExpression="^\d+\.\d{2}$" ValidationGroup="phone" ControlToValidate="Phone_TextBox">it should be 125.00 this format</asp:RegularExpressionValidator>
<asp:Button ID="Button1" runat="server" Text="Button" ValidationGroup="phone" /></div>
Here we have to discuss about how to validation UniqueIdentifiere using REGEX
Here is the Expression
^\w{7}-\w{4}-\w{4}-\w{4}-\w{12}
It wont allow spaces before or after the digits but it wont if there are only spaces so you need RequiredFieldValidator too
the RegularExpressionValidator to validate the phone number without using JavaScript. So something like this:
<asp:regularexpressionvalidator id="RegularExpressionValidator1"> ControlToValidate="TextBox1" ValidationExpression="\d+" Display="Static" EnableClientScript="true" ErrorMessage="Please enter numbers only" runat="server"/>
Hi Use this code.
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator
ID="valUserName" runat="server" ControlToValidate="TextBox1"
Display="Dynamic" ErrorMessage="Minimum length 6 characters"
ForeColor="" ValidationExpression=".{6}.*" ></asp:RegularExpressionValidator>
Here is the code how to limit the no.of charater entered by the user in TextBox , mostly this can be implemented on Post comment , Feedback , Message board ...
This example demonstrates on how are we going to limit the number of characters to be typed into the TextBox using JavaScript and display the remaining characters in a Label Control.
<script type="text/javascript" language="javascript">
function validatelimit(obj, maxchar)
{
if(this.id) obj = this;
var remaningChar = maxchar - obj.value.length;
document.getElementById('<%= Label1.ClientID %>').innerHTML = remaningChar;
if( remaningChar <= 0)
{
obj.value = obj.value.substring(maxchar,0);
alert('Character Limit exceeds!');
return false;
}
else
{return true;}
}
</script>
<body runat="server">
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" onkeyup="validatelimit(this,300)"> </asp:TextBox>
<asp:Label ID="Label1" runat="server" Text="0"></asp:Label>
</form>
</body>
Note: 300 is the MAX length of the characters in the TextBox..Just change the value of 300 based on your requirements..
Validate URL
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ValidationExpression="(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?" ControlToValidate="TextBox1" ErrorMessage="Input valid Internet URL!" ></asp:RegularExpressionValidator>
Here i update the Regex this will accept the URL like:
http://regxlib.com/Default.aspx | http://electronics.cnet.com/electronics/0-6342366-8-8994967-1.html
To validate US Zip Code
<asp:RegularExpressionValidator
ID="RegularExpressionValidator1"
runat="server"
ValidationExpression="\d{5}(-\d{4})?"
ControlToValidate="TextBox1"
ErrorMessage="Input valid U.S. Zip Code!"
></asp:RegularExpressionValidator>
Validate US Phone number
<asp:RegularExpressionValidator
ID="RegularExpressionValidator1"
runat="server"
ValidationExpression="((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}"
ControlToValidate="TextBox1"
ErrorMessage="Input valid U.S. Phone Number!"
></asp:RegularExpressionValidator>
Here we have to discuss how to validate US Social security number
<asp:regularexpressionvalidator id="RegularExpressionValidator1" runat="server" validationexpression="\d{3}-\d{2}-\d{4}"
controltovalidate="TextBox1" errormessage="Input valid U.S. Social Security Number!"></asp:regularexpressionvalidator>
To validate the fileupload control use Custom Validator and call this function on ClientValidateFunction property of Custom validator.
You can pass the file extension , Watever you want to allow..
function ValidateSFrontImageUpload(Source, args)
{
var fuData = document.getElementById('<%= FrontSImage_FileUpload.ClientID %>');
var FileUploadPath = fuData.value;
if(FileUploadPath =='')
{
// There is no file selected
args.IsValid = false;
}
else
{
var Extension = FileUploadPath.substring(FileUploadPath.lastIndexOf('.') + 1).toLowerCase();
if (Extension == "jpg" || Extension == "jpeg" || Extension == "png" || Extension == "gif")
{
args.IsValid = true; // Valid file type
}
else
{
args.IsValid = false; // Not valid file type
}
}
}
Here is the code
validation for tiny_mceEditor control
here is the code for validate the (Required field validation ) for the control< style="font-weight: bold;">OnClientClick="tinyMCE.triggerSave(false,true);
"
My site is worth$16,159.24Your website value?