regular expression for money and date on C#? - c#

Hello im searching regular expression for money and date on C#. i want to accept any positive number only in the format of 0.00 and not with a , like 0,00. Also im searching and expression for date with the format of dd/mm/yyyy . Can anyone help me? thank you
I have update the code to this
System.Text.RegularExpressions;
csReleaseDate = txtReleaseDate.Text;
String dateRegex = #"^\\d{2}/\\d{2}/\\d{4}$";
if (Regex.IsMatch(csReleaseDate, dateRegex)) {
lblRequired.Text = "is working";
} else {
lblRequired.Text = "is now working"; }
but nothing cites on the page

You are better off using the TryParse methods of DateTime and Decimal.
With DateTime you can use TryParseExact to match the exact format, and with Decimal if the format is right you can check if the value is positive.
These are better options for validating that strings are representing those types.

Don't use regular expressions for such a small problem. Get the money with a statement like that:
decimal parsedMoney;
if (decimal.TryParse(stringToParse, out parsedMoney))
{
// Do something with the money
}
And similar with the date like that:
DateTime parsedDate;
if (DateTime.TryParse(stringToParse, out parsedDate))
{
// Do something with the date
}
Edit
If you really want to use regex, then use \A\d+\.\d{2}\Z for searching your money and \d{2}/\d{2}/\d{4} for searching the date in your expected format.

Any time I've needed a regular expression I've used this web site for it.
Regular Expression Library web site.

"^\\d{2}/\\d{2}/\\d{4}$"
for date I think.

Related

Check if string starts with Regex number

I'm really new to Regex, so I'm looking for a way to check if my string starts with a certain regex. I found this on the Internet, however, I can't make it work with a custom regex.
I need to know if a specific line starts with
3.3. XXX
which is how you format German date. So the regex doesn't need to look up only this, but possibly
17.4. XXX
in both cases, I need to know if the input string starts with a date (which can have two possible notations, as stated above). So, for both it'd return true, however, it wouldn't for this:
15G
(for example).
Which regex is good to go for this?
Regex is not good at parsing number ranges so it can get pretty messy https://stackoverflow.com/a/15504877/1383168
To check if a string is a valid date you can use DateTime.TryParseExact
string s = "17.4. XXX"; DateTime d;
if (DateTime.TryParseExact(s.Split(' ')[0], "d.M.",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out d))
{
// matches
Debug.Print($"{d}"); // "4/17/2017 12:00:00 AM"
}
if you want a regex for detecting dd.mm type of date this your answer.
string testregex = "([0-2][0-9]|3[0-1]|[0-9])(.)(0[1-9]|1[0-2]|[0-9])(.)";
you can check any string to find match for this regex, Regex.IsMatch() returns true and statements in if block will execute.
string text="17.4 xxxxxx";
if (Regex.IsMatch(string test,testregex))
{
//do something
}

Date validator/format

I am trying to validate the format of date and also validate the date equal to or less than today in C# I am trying to achieve this in c# using regular expressions.
The formats I am trying to support are dd/mm/yyyy, dd-mm-yyyy, yyyy-mm-dd, yyyy/mm/dd.
var expressions = new List<Regex>();
expressions.Add(new Regex("^\\d{4}-((0\\d)|(1[012]))-(([012]\\d)|3[01])$"));
expressions.Add(new Regex("(((0|1)[1-9]|2[1-9]|3[0-1])\\/(0[1-9]|1[0-2])\\/((19|20)\\d\\d))$"));
return expressions;
Can somone please tell me what i am doing wrong in my reg ex and also suggest a better way to achieve this.
There is no need to use regular expressions for this; you can call DateTime.ParseExact or DateTime.TryParseExact with the permitted formats as an argument. Unlike regular expressions, this approach will also ensure that the user-provided date is valid (e.g., allowing "2016-02-29" but not "2015-02-29").
string inputDate = "2015-01-01";
DateTime dt;
bool validDate = DateTime.TryParseExact(inputDate,
new[] { "dd/MM/yyyy", "dd-MM-yyyy", "yyyy-MM-dd", "yyyy/MM/dd" },
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt);
Console.WriteLine(validDate ? dt.ToString("MM/dd/yyyy") : "Invalid date"); // 01/01/2015
There are a couple of problems here.
Your regular expression here
"^\\d{4}-((0\\d)|(1[012]))-(([012]\\d)|3[01])$"
Can only find date format with -, not with / (that is 1999-12-25 is valid but 1997/11/15 is not). If you want to change it, you should use
"\\d{4}(-|\/)((0\\d)|(1[012]))(-|\/)(([012]\\d)|3[01])$" //^ removed, \/ added
Which would match both 1999-12-25 and 1997/11/15 (edit: but will also match 1998/05-28!)
Likewise, your regular expression here
"(((0|1)[1-9]|2[1-9]|3[0-1])\\/(0[1-9]|1[0-2])\\/((19|20)\\d\\d))$"
Can only match 12/11/1954 but cannot match 12-11-1954. Some more, because you put (0|1)[1-9]|2[1-9], your regex cannot match 10-11-1954. Use
"((0|1)[0-9]|2[0-9]|3[0-1])(-|\/)(0[1-9]|1[0-2])(-|\/)(19|20)\\d\\d$"
instead
But seriously, unless is a must, it is a hellish task to parse (not to say to compare) DateTime value with Regex! You should just use DateTime.TryParse or DateTime.Parse together with TimeSpan for parsing and for comparison respectively.

Converting String Format "yyyy-MM-ddTHH:mm:ss.fffZ" to DateTime

I know this question has been asked a number of different ways, and I have looked at them all and none of the solutions seem to work for me. So, I am hoping that maybe you guys can give me a quick hand.
The input string is: "2000-01-01T12:00:000Z". I need to take that input string and convert it to DateTime so that it can be stored in the database.
I have been using ParseExact, but I keep getting the not recognized date string exception. Where am I going wrong?
inValue.LatestDepartTime = "2000-01-01T12:00:000Z";
DateTime _latestDepartTime = DateTime.ParseExact(inValue.LatestDepartTime, "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
Your format string needs to exactly match the input.
That includes the literal T and Z characters.
Use yyyy-MM-dd'T'HH:mm:ss.fff'Z'
The code is:
public DateTime convertIsoToDateTime (string iso)
{
return DateTime.ParseExact(iso, "yyyy-MM-dd'T'HH:mm:ss.fff'Z'", CultureInfo.InvariantCulture);
}
You need to include \\T and \\Z in your format string to match the literals T and Z.
You need to put single quotes around the T and Z:
DateTime parsedDateTime;
DateTime.TryParseExact(obj, "yyyy-MM-dd'T'HH:mm:ss'Z'", null, System.Globalization.DateTimeStyles.None, out parsedDateTime);
return parsedDateTime;
You don't specify the T in the pattern.
That said, you may want to have a look at the XmlConvert class, which provides the methods for converting this format.

Regular Expression Date and Time

Hi people I have the following express validation
[Required]
[RegularExpression("{0:d/M/yyyy HH:mm:ss}" ,
ErrorMessage = "Wrong Syntax")]
public string Posted { get; set; }`
But it does not allow the following input which am showing as a example of date and time:
12/12/2011 00:00:00 (I do not want these exact numbers the date and time should allow any numbers which is allowed logically by date and time standards)
I get the error message "Wrong Syntax" even when i input the correct code. What seems to be the problem. Any help will be really appreciated Thank You So Much
It is because RegularExpressionAttribute expects a Regex pattern and you are providing a .NET string format pattern (MSDN: RegularExpressionAttribute Class).
For basic format validation you would need to use something like:
[RegularExpression(#"\d{2,2}/\d{2,2}/\d{4,4} \d{2,2}:\d{2,2}:\d{2,2}")]
Replace your string in your RegularExpression attribute with a real regular expression. Try one of these from this library site of regex's:
http://regexlib.com/DisplayPatterns.aspx?cattabindex=4&categoryId=5&AspxAutoDetectCookieSupport=1
Try the first one.
For a complete guide to client and server validation in MVC (using something like a TextBoxFor), see my answer here:
Validate Date in MM/dd/YYYY format in mvc

How do I keep the 0's in a Date

I am trying to figure out how it is that I can keep the 0's or add them when I grab a date.
What Im getting is this:
6/15/2010
What I'm tring to get is:
06/15/2010
I have added it so that it checks the length to and if its less than 6 (im stripping the "/") it pads the left side. That solves the issue when the month is a single digit, but what about when the date is a single digit.
My ultimate goal is to have a date such as:
1/1/2010
read out like:
01/01/2010
Any suggestions would be greatly appreciated.
Use a custom format : dd/MM/yyyy, or in your case MM/dd/yyyy. Note the capital M, the small m gets you the minutes.
string s = DateTime.Now.ToString("MM/dd/yyyy");
You need to use a custom DateTime format string:
string str = someDate.ToString("dd/MM/yyyy");
It depends on the format of date you are using.
For instance, dd/MM/yyyy will produce 01/05/2009 and d/M/yyyy would produce 1/5/2009
A complete reference can be found there : http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
You want something like this:
string myDate = "1/1/2010";
DateTime date = DateTime.Parse(myDate);
string formattedDate = date.ToString("MM/dd/yyyy");
If the starting date is some other unrecognized format you could use DateTime.ParseExact();
Use DateTime.ParseExact() to parse the string into a valid datetime object and then use DateTime.ToString("dd/MM/yyyy") to get result in desired format.

Categories