Avatar of 1jaws
1jawsFlag for United States of America asked on

validation for lenght of the textbox

I have credit card textbox that it has maxleght is set to 16 but i need to put a validation on that if user enters less than 16 digits it should complain.. which validation is good for that?
ASP.NET

Avatar of undefined
Last Comment
1jaws

8/22/2022 - Mon
copyPasteGhost

required and then you'll need a custom
copyPasteGhost

[aspx]

<asp:TextBox ID="txtCred" runat="server" MaxLength="16" />
      <asp:RequiredFieldValidator
         ID="RequiredFieldValidator1" ControlToValidate="txtCred" runat="server" ErrorMessage="Must enter Credit Card number!"></asp:RequiredFieldValidator>
       <asp:CustomValidator ControlToValidate="txtCred" ID="CustomValidator1"
           runat="server" ErrorMessage="Must be 16 characters long!"
           onservervalidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
[C#]

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args) {
      args.IsValid = args.Value.Length == 16;
   }
JacobBushong

You can use a custom validator or you can do it manually with textbox.text.length
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
ASKER
1jaws

is there anyway to not user code behind? or have to for that?
copyPasteGhost

why don't you want to use the code behind??

you can do it inline...

<script language="C#" runat="server">
      protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args) {
      args.IsValid = args.Value.Length == 16;
   }
    </script>

Many people write code this way. You will need the extra .cs file.

ASKER
1jaws

what is actually differrent between writing protected void in Javascript and codebehind. which one is better? also do I need to add anthing in CompareValidator1 ?
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ASKER CERTIFIED SOLUTION
copyPasteGhost

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ASKER
1jaws

Thank you!