Showing posts with label Validation. Show all posts
Showing posts with label Validation. Show all posts

Validate Checkbox and Checkboxlist in easy way

Posted by Venkat | Labels: , ,

Hi Good Evening Techies.

I saw the post that has been asked number of times ie: how to validate the Checkbox and checkboxlist
so we can validate the Both of this using the Javascript or JQuery , but here I am going to make it much more easy ie: 4guysformula Provides the Control which can added to our toolbox then you can work these similar to the other validation Control

Validation Control for Checkbox and Checkboxlist

Go to the page down - Get the control ie: dll file ie: skmvalidators.dall place the file on Bin Folder of your project then add the dll file to your toolbox. then drag and drop to your aspx page & set some property thats it.

Alternatively Download the file here skmValidators.rar

Validate Indian Mobile Number

Posted by Venkat | Labels: ,

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+


Atlast i have to check whether user entered Number is 10 digit or not and also it should be valid Mobile Number
Regex ^[9][0-9]{9}$


This Regex which first digit should be 9 then followed by 9 digits and totally it accept only 10 digits.

Paypal Code - Validate Credit Card & CreditCard Payment through Website Payments Pro method

Posted by Venkat | Labels: , , ,

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);
   }
}

I have the task of payment method through paypal pro using Credit Card.i was

googled a lot with paypal site , fourms and came with the sample code.

The PayPal Name-Value Pair API (NVP API) enables you to leverage thefunctionality of the PayPal API by simply sending an HTTP request to PayPal and specifying request parameters using name-value pairs. The NVP API is a lightweight alternative to the PayPal SOAP API and provides access to the same set of functionality as the SOAP API.

Ref: https://www.paypal.com/IntegrationCenter/ic_nvp.html

Here i am usin NVP API for payment through CreditCard using website Payment Pro

Method , we can also use SOAP API for this we need to do

1)setExpressionCheckout

2) DoExpressionCheckout

3) GetExpressionCheckout.

Either we can use API or through Code. I am Registering on Sandbox.paypal to check the code. we have to create the Buyer , seller Account to check the amount has been transferred or not , so it will automatically create the creditcard no, cardtype for the test account, we have to use this to check the Amount Transfer
or not. While testing , the amount was not deducted on the buyer account but it will credited on Seller account  as this is sanbox test, this is not an issue ,while you upload it on live , it will work smoothly.As i was tested with Sandbox - so you can check it on live.

One of the main advantage of this method is , it will not redirect the user to paypal site,instead the process has been doing on background from the same site after successfull transaction it will give the Transactionid ,
act etc.. so you can store this thing on DB.


While page Designing make sure you have these Fields

1) Card Type

2) Textbox for CreditCard Number

3) Expire Date  / Expire Month

4) Pay button / Cancel button

paybutton_Click
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;
        } 

Finally , once your Transaction is success you will get the output ie:TransactionID with ack

EX: Output

ACK=Success&TIMESTAMP=date/timeOfResponse
&CORRELATIONID=debuggingToken&VERSION=2.300000&BUILD=buildNumber
&TOKEN=EC-3DJ78083ES565113B&EMAIL=abcdef@anyemail.com
&PAYERID=95HR9CM6D56Q2&PAYERSTATUS=verified
&FIRSTNAME=John&LASTNAME=Smith...&AMT=15&TRANSACTIONID=24527936A38716

Regex for Indian Phone Numbers

Posted by Venkat | Labels: ,

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

Validation which accept( empty , numeric or Float values)

Posted by Venkat | Labels: ,

Now we have to discuss about the validationexpression ie:

the textbox should accept empty values , numeric ( float ) .

Implementation Code :

^\d*\.?\d*$

HTML


<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" />
Matches

( ) -> empty value
4535
520.20
2.54

Non-Matches

21.0dfdf
47854
Rpks

Validate Decimal numbers

Posted by Venkat | Labels: ,

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>


Matches

142.00
254.25 etc

Non-Matches

214
25.0
254.5
254.355

code:

Validate UniqueIdentifier

Posted by Venkat | Labels: ,

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}

Validate the numbers

Posted by Venkat | Labels: ,

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"/>

Textbox should allow minimum 5 Character

Posted by Venkat | Labels: ,

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>

Limit the Maximum number of Characters in the texbox

Posted by Venkat | Labels: , ,

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

Posted by Venkat | Labels: ,

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 

Validate US Zip Code

Posted by Venkat | Labels: ,

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

Posted by Venkat | Labels: ,

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>

Validate US Social Security Number

Posted by Venkat | Labels: ,

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>

Validation for FileUploadControl

Posted by Venkat | Labels: ,

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
}
}
}

Validation for Tiny_MceEditor Control

Posted by Venkat | Labels: , ,

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);"

PayOffers.in