?
Solved

RangeValidator on date with 4 controll digits

Posted on 2009-02-22
21
Medium Priority
?
422 Views
Last Modified: 2012-05-06
Hi,

I have am trying to do a range validator for a date with four controll digits. Is that possible?
It works fine if I just use the date and no control digits.

This is what I have on page load:
RangeValidator1.MaximumValue = DateTime.Today.ToString("yyyy/MM/dd");

But I need my date to be like this:
19950121-4015

So I guess it doesnt work because of the 4 last digits. Is there away around this problem?

Also do I really have to write the minum value like this?
1850/1/1

I would like the minimuValue to be like
18500101
but then I get a error message.

So what do I want?
I want a range validator to be able to go between 1850 to todays date.
I want my input in the text box to be like this

OK: 19990101-2222
NOK: 18490122-2222
NOK: 20100122-2222
OK:18500102-2222


OR

is there another way to check it? I just have to have between one date and today. Maybe code it into the application?

 
0
Comment
Question by:Mickeys
  • 12
  • 9
21 Comments
 
LVL 21

Expert Comment

by:MogalManic
ID: 23711465
It seems you cannot use time in the range validator.  The format of the min/Max value is based on your current culture setting or YYYY/MM/DD.
  http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.rangevalidator.maximumvalue.aspx

Here is a sample.  Is this what you want to do?:
    <form id="form1" runat="server">
        <asp:TextBox ID="txtDate" runat="server" />
        <asp:RangeValidator ID="txtDateValidate" runat="server" ControlToValidate="txtDate" Type="date" ErrorMessage="Not a valid date"/>
        <asp:Button ID="btnValidate" runat="server" Text="ValidateDate" CausesValidation="true" />
    </form>
 
....Code Behind...
    protected void Page_Load(object sender, EventArgs e)
    {
        this.txtDateValidate.MaximumValue = DateTime.Now.ToShortDateString();
        this.txtDateValidate.MinimumValue = (new DateTime(1850, 01, 01)).ToShortDateString(); 
    }

Open in new window

0
 

Author Comment

by:Mickeys
ID: 23712164
With that code you provide me the MaximumValue will be (if runned today)

23-02-2009

What I need is that when I enter in my text box for example:
20081112-3333
this will be a valid string.

If I enter:
20090224-3333
this will be NOT a valid string.

So I guess I have to take out the text value. Compare the first string before the - sign or???

/M
0
 
LVL 21

Expert Comment

by:MogalManic
ID: 23712365
You will have to create a CustomValidator.  The RangeValidator can only validate ONE value at a time.  You are entering two values (a date and -3333 (is this time?)).

You will have to choose if you want the validation on the client or on the server.  If on the client, then you will have to write the validatation code in JavaScript.  If on the server, you can write the validation code in c#.
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 

Author Comment

by:Mickeys
ID: 23712897
Ok.

I add a CustomValidator.
I enter a "Social Security number" wich is the date plus four digits. It is writen like this
19990121-3333
199901213333
9901213333

All this is already checked for so this is OK to enter. But what I need is that it cant be higer than todays date.

It is on the server side so I am able to write C# code. All I need to know is how to do this?

Will I get the date into a string with DateTime.Now and then I have to break down the input in the text box that I recive? Where will the check then be done? In the page_load or when?
0
 
LVL 21

Accepted Solution

by:
MogalManic earned 1000 total points
ID: 23713115
It is on the ServerValidate event on the CustomValidator.  The code will be something like this:



Then on the code behind
protected void ValidateSSN(object source, ServerValidateEventArgs args)
{
     DateTime today=DateTime.Now;
     args.IsValid=IsValidSSN(args.Value, today);  
}

Open in new window

0
 

Author Comment

by:Mickeys
ID: 23713449
Well here I get stuck. :-(

I guess the CustomValidator name is ValidateSNN

If I then enter this code (this is just to get the stuff running) I get error:

Error      1      The type '_Default' already contains a definition for 'ValidateSSN'      C:\Documents and Settings\MFL\Dokumenter\Visual Studio 2005\WebSites\WebSite\WebSite\Inlamning1\Default.aspx.cs      27      20      C:\...\Inlamning1\



   protected void ValidateSSN(object source, ServerValidateEventArgs args)
    {
        DateTime today = DateTime.Now;
        string Value = "";
        bool IsValid = IsValidSSN(Value, today);
    }


    protected bool IsValidSSN(string Value, DateTime today)
    {
        return true;
    }
0
 
LVL 21

Expert Comment

by:MogalManic
ID: 23715862
You cannot have a function and a control with the same name, rename the customValidator to something like ValidateTxtSSN.
0
 

Author Comment

by:Mickeys
ID: 23719359
Aha.

So I guess this will be the last question.
How do the Validation know if it is OK or not?

I mean what will I return from the method? It is a void so I dont see how the validation get to know if it is ok or not?

0
 
LVL 21

Expert Comment

by:MogalManic
ID: 23720655
Your method
protected bool IsValidSSN(string Value, DateTime today)
    {
        return true;
    }
should do the validation.  just return false if the date part is incorrect.
0
 

Author Comment

by:Mickeys
ID: 23720688
That wont work.

My ID on the valutation ValidateTxtSNN
ServerValidate: ValidateSNN

and my code

protected void ValidateSSN(object source, ServerValidateEventArgs args)
    {
        string today = DateTime.Today.ToString("yyyy/MM/dd");
        string value = pnrTextBox.Text;
        bool IsValid = IsValidSSN(value, today);
    }


    protected bool IsValidSSN(string value, string today)
    {
        //Ta bort /
        today = today.Replace("-", "");
        value = value.Replace("-", "");
        value = value.Replace("+", "");
        bool flag = false;

        if (value.Length == 10)
        {
            value = value.Remove(6, 4);
            value = String.Concat("19", value);
        }

        else
        {
            value = value.Remove(8, 4);

        }


        if (String.Compare(value, today, true) > 0)
        {
            flag = true;
        }

        return flag;
    }


This will not make it say that it is a errror (the date is more than today)
0
 
LVL 21

Expert Comment

by:MogalManic
ID: 23720699
Your logic is reversed.  Return True if it is valid and false if it is invalid.
0
 

Author Comment

by:Mickeys
ID: 23720848
Sorry but I still dont get an error message as I think I should. Even if I switch so I dont get them in reversed. What is it that I dont get?

isnt this valuation supposed to be as all the rest of the valutaions that I can choose?

I have a validationSummary and everything else is showing in there if it doesnt work. But this one is just running without any message
0
 

Author Comment

by:Mickeys
ID: 23721342
Here is the code:

    protected void ValidateSSN(object source, ServerValidateEventArgs args)
    {
        string today = DateTime.Today.ToString("yyyy/MM/dd");
        string value = pnrTextBox.Text;
        args.IsValid = IsValidSSN(value, today);
    }

Lets say I get false back on args.IsValid. Isnt it supposed to bring up the ErrorMessage I have in the ValidationSummary and on the CustomValidator? The program is just running on as if nothing have happened.
0
 
LVL 21

Expert Comment

by:MogalManic
ID: 23721655
Can I see your aspx page?

You need to have a button or something with the CausesValidation="true" set so that a postback event occurs that causes the validators to run.
0
 

Author Comment

by:Mickeys
ID: 23721733
Here you go:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
   
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="pnrTextBox" runat="server"  Style="z-index: 100;
            left: 199px; position: absolute; top: 178px"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Style="z-index: 101;
            left: 254px; position: absolute; top: 224px" Text="Verifiera" Width="99px" />
        <asp:Label ID="Label1" runat="server" Style="z-index: 102; left: 104px; position: absolute;
            top: 179px" Text="Personmmer:"></asp:Label>
        &nbsp;&nbsp;
        <asp:Label ID="Label3" runat="server" Style="z-index: 103; left: 374px; position: absolute;
            top: 179px" Text="(ÅÅMMDD-NNNN)"></asp:Label>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="pnrTextBox"
            Display="Dynamic" ErrorMessage="Var snäll och skriv in ett personnummer" Style="z-index: 104;
            left: 519px; position: absolute; top: 179px">*</asp:RequiredFieldValidator>
        <asp:ValidationSummary ID="ValidationSummary1" runat="server" Style="z-index: 105;
            left: 159px; position: absolute; top: 265px" />
        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="pnrTextBox"
            ErrorMessage="Fel format på personnumret" Style="z-index: 106; left: 536px; position: absolute;
            top: 179px" ValidationExpression="\b(?:19|20)?\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])[-+]?\d{4}\b" Display="Dynamic">*</asp:RegularExpressionValidator>
        &nbsp; &nbsp;
        <img src="bilder/topp_anmalan_smal.jpg" style="z-index: 108; left: 0px; position: absolute;
            top: 0px" />
        &nbsp;&nbsp;
        <asp:CustomValidator ID="ValidateTxtSSN" runat="server" ControlToValidate="pnrTextBox"
            Display="Dynamic" ErrorMessage="Ledsen men du måste ha datum fram tills idag."
            OnServerValidate="ValidateSSN" Style="z-index: 109; left: 558px; position: absolute;
            top: 179px">*</asp:CustomValidator>
   
    </div>
    </form>
</body>
</html>
0
 
LVL 21

Expert Comment

by:MogalManic
ID: 23723040
The problem was a logic error in the event handler.  You were setting a local variable to IsValid instead of args.IsValid.  The corrected function is below:
    protected void ValidateSSN(object source, ServerValidateEventArgs args)
    {
        string today = DateTime.Today.ToString("yyyyMMdd");
        string value = pnrTextBox.Text;
        args.IsValid = IsValidSSN(value, today);
    }

Open in new window

0
 

Author Comment

by:Mickeys
ID: 23723122
No. Check 3 comments up. There is the same code as you have in yours. I also took yours incase I did something wrong but it is still the same.

Sorry for being a pain in the....
0
 
LVL 21

Expert Comment

by:MogalManic
ID: 23726009
So your ValidateSSN() function has
    args.IsValid = IsValidSSN(value, today);
instead of
   bool IsValid = IsValidSSN(value, today);


What about line 3?  It should be
  string today = DateTime.Today.ToString("yyyyMMdd");  //Note:no '/' in the format template
0
 

Author Comment

by:Mickeys
ID: 23731005
-Goodmorning.

Well I have debugeit and it isn not the line 3 either. You see the today string gets something like this:-
2009-03-25 and then in my method I do remove of the "-"

today = today.Replace("-", "");

That means that everything works fine so far. I get a false or true depending on what I type in so that is also correct. The thing that is not correct is that I dont get the expression to signal ERROR.

So is it some propety that I have forgot to put into the CustomValidation?

I will give you the code that I have right now.

default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
    {

    }



    protected void ValidateSSN(object source, ServerValidateEventArgs args)
    {
        //string today = DateTime.Today.ToString("yyyyMMdd");
        //string value = pnrTextBox.Text;
        //args.IsValid = IsValidSSN(value, today);


        string today = DateTime.Today.ToString("yyyyMMdd");
        string value = pnrTextBox.Text;
        args.IsValid = IsValidSSN(value, today);

    }


    protected bool IsValidSSN(string value, string today)
    {
        //Ta bort /
        today = today.Replace("-", "");
        value = value.Replace("-", "");
        value = value.Replace("+", "");
        bool flag = true;

        if (value.Length == 10)
        {
            value = value.Remove(6, 4);
            value = String.Concat("19", value);
        }

        else
        {
            value = value.Remove(8, 4);
        }


        if (String.Compare(value, today, true) > 0)
        {
            flag = false;
        }

        return flag;
    }

    public void Button1_Click(object sender, EventArgs e)
    {
....... alot of checks....and this works fine

}


and the default.aspx
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
   
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="pnrTextBox" runat="server"  Style="z-index: 100;
            left: 199px; position: absolute; top: 178px"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Style="z-index: 101;
            left: 254px; position: absolute; top: 224px" Text="Verifiera" Width="99px" />
        <asp:Label ID="Label1" runat="server" Style="z-index: 102; left: 104px; position: absolute;
            top: 179px" Text="Personmmer:"></asp:Label>
        &nbsp;&nbsp;
        <asp:Label ID="Label3" runat="server" Style="z-index: 103; left: 374px; position: absolute;
            top: 179px" Text="(ÅÅMMDD-NNNN)"></asp:Label>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="pnrTextBox"
            Display="Dynamic" ErrorMessage="Var snäll och skriv in ett personnummer" Style="z-index: 104;
            left: 519px; position: absolute; top: 179px">*</asp:RequiredFieldValidator>
        <asp:ValidationSummary ID="ValidationSummary1" runat="server" Style="z-index: 105;
            left: 159px; position: absolute; top: 265px" />
        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="pnrTextBox"
            ErrorMessage="Fel format på personnumret" Style="z-index: 106; left: 536px; position: absolute;
            top: 179px" ValidationExpression="\b(?:19|20)?\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])[-+]?\d{4}\b" Display="Dynamic">*</asp:RegularExpressionValidator>
        &nbsp; &nbsp;
        <img src="bilder/topp_anmalan_smal.jpg" style="z-index: 108; left: 0px; position: absolute;
            top: 0px" />
        &nbsp;&nbsp;
        <asp:CustomValidator ID="ValidateTxtSSN" runat="server" ControlToValidate="pnrTextBox"
            Display="Dynamic" ErrorMessage="Ledsen men du måste ha datum fram tills idag."
            OnServerValidate="ValidateSSN" Style="z-index: 109; left: 558px; position: absolute;
            top: 179px">*</asp:CustomValidator>
   
    </div>
    </form>
</body>
</html>



It must be some property that must be set since it doesnt pass true or false back to the validation.
Should something more be set than:
ControlTOValidate
ErrorMessage
Text
IDServerValidate









0
 

Author Comment

by:Mickeys
ID: 23742879
and I found the missing part. :-)

A validation failure doesn not automatically prevent other page events from ocurring. You need to add "if (Page.IsValid)" logic to your button's event handler to prevent validation-dependent code from executing unless the page's validators' conditions are met.
0
 

Author Closing Comment

by:Mickeys
ID: 31549738
thx for all the help
0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
Hello there! As a developer I have modified and refactored the unit tests which was written by fellow developers in the past. On the course, I have gone through various misconceptions and technical challenges when it comes to implementation. I would…
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…
Stellar Phoenix SQL Database Repair software easily fixes the suspect mode issue of SQL Server database. It is a simple process to bring the database from suspect mode to normal mode. Check out the video and fix the SQL database suspect mode problem.
Suggested Courses
Course of the Month7 days, 10 hours left to enroll

607 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question