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
Related
I have some issue with the return of a WEB API.
This API processes the data and returns an object of type List <Dictionary <string, object >>.
The problem is that when returning a date (datetime) the return format change depending on the server on which the site is installed.
For example I have these two cases:
the first is the correct size, while the second is to wrong.
I have the following statement in the code that converts (should convert) the date to the desired format:
dict.Add(dc.Caption, ((DateTime)dr[dc.Caption]).ToString("yyyy-MM-dd HH:mm:ss"));
Can you help me?
Bye
Davide
The colon (:) in a DateTime format string does not always translate to a colon, it stands for "the time separator according to the current culture". See also MSDN: Custom Date and Time Format Strings.
You can see this in this code sample, using the Finnish culture, where the period is used as a time separator:
var finnishCulture = new CultureInfo("fi-FI");
Thread.CurrentThread.CurrentCulture = finnishCulture;
Console.WriteLine(DateTime.Now.ToString());
Console.WriteLine(DateTime.Now.ToString("HH:mm"));
Console.WriteLine(DateTime.Now.ToString(#"HH\:mm"));
This prints:
7.3.2017 15.58.47
15.58
15:58
Perhaps let WebAPI do the serialization for you, or if you're sure you want to serialize it yourself, escape the colon: \:.
I have some data picked up from an excel file.
I want to validate that the user has entered a valid date time string. I have tried to use DateTime.Parse method but found that certain values seem to be accepted.
For example,
If I submit 3.3 as a date time this is accepted by the DateTime.Parse method as a valid date time and outputs 03/03/2012 00:00:00
I want to want to block this. Only allowing the user to enter correctly formatted date times.
So for example a user could supply 03/03/2012 or 03/03/2012 12:30:00 but not values like 01022012 or 3.3.2012
Any Ideas?
You want to use DateTime.ParseExact or DateTime.TryParseExact
This allows you do parse from a date format string of your choice.
http://msdn.microsoft.com/en-us/library/system.datetime.tryparseexact.aspx
Examples here:-
http://msdn.microsoft.com/en-us/library/ms131044.aspx
You can use RegEx to to this. Something like this should help #"\d{2}/\d{2}/\d{4}(\s+\d{2}\:\d{2}\:\d{2})?"
You can handle it on the client side with various jquery plugin/functions like this or a simple Google search can return many other useful results.
if you want to handle it on the server side, (I am not sure on what project you are working) but depending over it you can write your own method/use Regex or Data Annotation MVC.
If you are still having trouble try adding few details about your project such as Language, Architecture etc. that would help more in providing the right solution.
Hope it helps. Thankyou
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.
I have ASP.NET MVC site with ordinary Html Form with text field to put Date in.
<input type="textbox" name="date"/>
Controller method looks like:
void DoSomething(DateTime date)
{
....
}
As users have different locales and habits how to enter date how shall I handle DateTime formats? I guess there should be code that try to parse string to several date time formats. Can I handle all DateTime(s) params centralized without Helper class call every time controller expects DateTime ? How can I take into account user locale ?
Thank you in advance!
You can use jQuery UI datepicker for example, and set the format. This will also be a better user experience then a simple textbox..
$('#datetime').datepicker({ format: 'yy-mm-dd hh:ii' });
Datepicker provides support for localizing its content to cater for
different languages and date formats.
Best practice here is to force users to enter only one date format.
You can achieve this with RegularExpression validation and date picker such as JQuery Datepicker.
UPDATE :
Also, if you not want to force users to one format, please check DateTime.Parse method of C# but it is a little tricky and you need to be careful while using it. There might be some conflicts. (E.g. 2011-01-01 can be seen as two different dates if you don't know the format.)
If you try to handle every type of formats you will have to provide the type of the format.
Issue that is commonly faced is mm-dd-yy and dd-mm-yy format say 02-01-11. Question is is it 2 Jan or 1 Feb.
If you are able to send the correct format type there shouldn't be any problem other than the input string could be wrong itself.
The best solution (which you may not be looking for) is to validate date/time while user inputs in the form. Like making separate drop down box(or just text box) for date and month.
I use asp.net 4 and c#.
I need to use a WebControl of type Validation namely RegularExpressionValidator to detect data inputed in a TextBox that IS NOT in format yyyy-MM-dd (String).
Any idea how to write the RegEx to apply ot this control?
Thanks
Here's one possible regex:
^\d{4}-((0\d)|(1[012]))-(([012]\d)|3[01])$
Note: this will prevent months >12 and days >31, but won't check specific months for length (ie it won't block 30th Feb or 31st Apr). You could write a regex to do that, but it would be quite lengthy, and 29th Feb is always going to give you problems in regex.
I'd say if you need that kind of fine-grained validation, you're better off parsing the date with a date library; regex isn't the tool for you. This regex should be sufficient for basic pre-validation though.
I've also gone lenient on the year; just checking that it's four digits. But if you want some sort of sanity check (ie within certain bounds), it shouldn't be too hard to add. Foe example, if you want to match only dates in the this century, you would replace the \d{4} at the beginning of the regex with 20\d{2}. Again, trying to validate a date with excessive accuracy in regex is going to be difficult and you should use a date parser, but you can get basic century-level matching quite easily to prevent the user entering anything really silly.
Finally, I've put ^ and $ to tie off the ends of the string so it can't match if the user enters a valid date and extra characters as well. (You may want to add a string length validator for this as well).
Hope that helps.
Spudley's answer above allows 00 for day and month.
I fixed it :
^\d{4}-((0[1-9])|(1[012]))-((0[1-9]|[12]\d)|3[01])$
Note: neither of these expressions check for days in a month that are invalid, e.g. 04/31, 06/31 or 02/29 on non-leap years.
Regular expression \d\d\d\d-\d\d-\d\d should do the trick.
I would like to add a little change in Spudley's answer:
^\d{4}$|^\d{4}-((0?\d)|(1[012]))-(((0?|[12])\d)|3[01])$
so you can use date like 2013-5-5 (month and date is not necessary the zero but can be used)
Hope it helps.
Another implementation for ISO 8601 structured dates:
^\d{4}-\d{1,2}-\d{1,2}\s\d{1,2}:\d{1,2}:\d{1,2}.?\d{0,}$
It's not quite as strict, and will accept incorrect dates, but it should validate that it follows the ISO 8601 structure even if the date is a non-existent one. It should also be fairly simple to understand for anyone with a basic Regex understanding.
If you really want to ensure the date is correct, and work with it, run DateTime.TryParse() on it.
(19|20)[0-9]{2}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])
mach result:
1999-09-12
((([0-9][0-9][0-9][1-9])|([1-9][0-9][0-9][0-9])|([0-9][1-9][0-9][0-9])|([0-9][0-9][1-9][0-9]))-((0[13578])|(1[02]))-((0[1-9])|([12][0-9])|(3[01])))|((([0-9][0-9][0-9][1-9])|([1-9][0-9][0-9][0-9])|([0-9][1-9][0-9][0-9])|([0-9][0-9][1-9][0-9]))-((0[469])|11)-((0[1-9])|([12][0-9])|(30)))|(((000[48])|([0-9]0-9)|([0-9][1-9][02468][048])|([1-9][0-9][02468][048]))-02-((0[1-9])|([12][0-9])))|((([0-9][0-9][0-9][1-9])|([1-9][0-9][0-9][0-9])|([0-9][1-9][0-9][0-9])|([0-9][0-9][1-9][0-9]))-02-((0[1-9])|([1][0-9])|([2][0-8])))
This is the regex for yyyy-MM-dd format.
You can replace - with \/ for yyyy/MM/dd...
Tested working perfect..