asp.NET MVC Model State Validation Issues - asp.net

I am having issues adding validation methods to a couple of controls in my MVC app. I use the following to test for the mm/dd/yyyy format:
if (!Regex.IsMatch(candidateToEdit.availability.StartDate.ToShortDateString(), #"giantregex"))
ModelState.AddModelError("availability_StartDate", "Start date must be in the mm/dd/yyyy format.");
//giantregex is a giant regular expression omitted for clarity
In my view I have:
<%= Html.ValidationSummary("Edit was unsuccessful. Please correct the errors and try again.") %>
<%= Html.ValidationMessage("availability_StartDate", "*")%>
For whatever reason the error text is not being displayed, it acknowledges there is an error and the start of the list is generated, but the "Start date must be in the mm/dd/yyyy format." is not displayed. It validates if you put in the date correctly.

I think the problem here is you're testing an actual DateTime type against a regular expression. Because they have entered an invalid date time format in the text box, it is never actually parsed into an actual DateTime where ToShortDateString() could be invoked on it. Therefore your regular expression validation is never actually occurring.
You'll need to adopt the ViewModel pattern where you expose all potential parsing problems as strings first (such as "candidateToEditViewModel.AvailabilityStartDateString") or implement client side validation and program defensively.

I think you need to include a validation summary to get the message
<%= Html.ValidationSummary() %>
EDIT: Try putting a "." instead of a "_" as your property name in the AddModelError call, like this:
Instead of:
ModelState.AddModelError("availability_StartDate", "Start date must be...");
try this:
ModelState.AddModelError("availability.StartDate", "Start date must be...");

The sample you gave works at my testproject. Can you try to reproduce the error in a freshly created project?

Related

How to pass multiple server values to the web method when using AJAX Toolkit CascadingDropDowns

I need to pass in multiple server values to the web method.
If I pass through a single value in the ContextKey, like this:
ContextKey='<%# this.someValue.ToString()%>'”
I get the value, no problem.
But as soon as I try passing multiple variables, like this:
ContextKey='someKey1:<%# this.someValue1.ToString()%>;someKey2:<%#this.someValue2.ToString()%>'
I end up getting the literal string.
I used this post to get the syntax on how to pass multiple parameters:
http://selftaughtprogrammer.com/2012/11/01/how-to-pass-extra-parameters-when-using-ajax-toolkit-cascadingdropdowns-with-a-database/
Attribute values in ASP.NET markup can be either literals, or server-binded snippet, you cannot mix them in arbitrary order. However this is not a big deal, since server-binded snippet gives you everything need to form the necessary value. Say via string.Format:
ContextKey='<%# string.Format("someKey1:{0};someKey2:{1}", this.someValue1, this.someValue2) %>'

How do I validate a zip code in visual basic?

I am supposed to use the regularExpressionValidator to verify a ZIP code for a basic webpage I'm making. If the Zip code is valid, the submit button's click event procedure should display the message "Your ZIP code is" followed by the ZIP code and a period.
I don't know how to do an "if" statement to check to see if the zip is valid or not
**Why does the value = 0 when I enter 60611-3456
...don't know how to do an "if" statement...
You were assigned to use a RegularExpressionValidator, and this sounds like homework. If so, it also sounds like the purpose of the assignment is to make this happen without writing any if statements at all.
The validator controls have a feature where a postback event will not occur if validation fails. You use a correct regular expression with a correctly configured validator control, and the code that shows the "Your zip code is..." message will never run. Configuring the validator control is the point of the assignment; you need to do that part on your own. But finding an acceptable regular expression is a distraction from the real learning, and so I don't mind just giving that to you:
^\d{5}(-\d{4})?$
The issue is that your regular expression indicates the four digits must exist if you have the dash. Generally that would be okay but since you're using an input mask the dash always exists, even when it's only five digits. Try the following expression.
ValidationExpression="\d{5}-?(\d{4})?$"
Hope it helps.

Error converting date for Calendar in asp.net

I have written code for two checkboxes:
string sdate= Convert.ToDateTime(txtFromDate.Value);
string edate=Convert.ToDateTime(txtEndDate.Value);
I am getting the following error: "String was not recognized as a valid DateTime".
Well, it's reasonably clear: the input string wasn't in an appropriate format. I suggest that instead of using Convert.ToDateTime, you use DateTime.TryParseExact and specify the format string (or strings) that you expect the user to enter.
Using TryParseExact instead of just ParseExact means you can detect if the user has entered an incorrect date without an exception being thrown - and you should check for that. Basically the return value of TryParseExact indicates success or failure, and an out parameter is used to capture the parsed date/time on success.
What I hadn't noticed to start with is that you're then trying to assign a DateTime value to a string. That's not going to work - but we can't advise you on what you should be doing instead without knowing what you want to do with the data. I suspect you want to change sdate and edate to be DateTime variables instead.

asp.net dynamic data application won't accept input with "<" in it

I'm new to using asp.net dynamic data apps.. I just generated a simple app from my schema, and in one table I'm trying to insert a record where one of the fields is a varchar(255) field. I am finding that any input that has the "<" character in it will cause the app to throw an error when you try to save it, with the exception being if "<" is the last character in the input string.
Since the editinsert function is some ajax based call, it just gives me a generic javascript error indicating whatever webservice it tried to hit for the update threw a 500 error and I have no idea how to debug this.
I would guess it's one of two things:
1 - You're triggering asp.net's built-in request validation. You can turn it off by adding the following to your page:
<%# Page validateRequest="false" %>
(You can read more about it at http://www.asp.net/%28S%28ywiyuluxr3qb2dfva1z5lgeg%29%29/learn/whitepapers/request-validation/)
OR
2 - You're not using parameterized SQL querys so your doing something like:
"SELECT * FROM Customers WHERE FirstName = " + input
And this is causing invalid SQL when "input" has an SQL operator in it (such as ">")

Displaying proper date format depending on culture

I am using a control for a popup calendar date picker. This uses a javascript function, SetText, to set the textbox to the given date. I can't change anything in the calendar control itself but I can override the SetText function. The SetText javascript just takes the TextBox name and the date value in string format and sets the TextBox to the string.
The problem:
I need to display the date in the format "April 30".
Easy to do. Use getMonth() and getDate() where I can parse the information from there.
Now, I need to make sure this shows correctly for different cultures. For example, the UK shows dates as "30 April". Since the code-behind(c#) could be sending the date in the UK format how do I know in the javascript that they're using UK(dd/mm/yyyy) and not US(mm/dd/yyyy)?
The browsers navigator language could be set to one setting while the server is set to another to cause a January 4 as April 1 mismatch.
You are using the Microsoft Ajax Framework, this framework defines a set of "client-side type extensions" which provide added functions or "extensions" to the JavaScript base types.
The Date Type Extensions is what you're looking for, specifically the Date.parseLocale function.
With this function you can parse a string, using a given format.
You can synchronize your server-side and client-side culture by setting the ScriptManager.EnableScriptGlobalization property to true, and use the Date.parseLocale function without specifying any format.
Give a look to this article:
Walkthrough: Globalizing a Date by Using Client Script
See toLocaleString and related functions.
If you control the backend, why not just send a timestamp and push it into Date object?
As for formatting on the client side, since I was already using Dojo, I solved this problem by using dojo.date.locale.format. It was completely painless.
Locale is detected automatically or can be set arbitrarily.
Shorthand format options (e.g.: long short)
Data selectors (e.g.: time, date)
Ability to specify an arbitrary date/time pattern (probably not application to this application, but still useful).
Tutorial: http://docs.dojocampus.org/dojo/date/locale
API doc:
http://api.dojotoolkit.org/jsdoc/1.3/dojo.date.locale.format
Date format descriptions: http://www.unicode.org/reports/tr35/tr35-4.html#Date_Format_Patterns
Three things you could use:
1) toLocaleString - As suggested already. The problem with this is when sending a string of "4/1/2009" this can result in a couple things. January 4 or April 1.
2) navigator.language and navigator.systemLanguage - After you get the date string you can check to see what language the system is in and parse the date from there. The problem with this and solution 1 is what if you have a UK server and the browsers machine is US. You will have the code behind sending April 1 as 1/4/2009 where the javascript will read the string as whatever language the clients browsers is. So, UK server and US browser will give you a wrong result.
3) Use Code Behinds Culture - Create a variable in your javascript that when the page loads, it will call a function in your code behind that returns this.Page.Culture from there, you will know what culture the string is being sent back as. This will eliminate the mismatch that the first two solutions can cause. It will take a little extra work to make sure it's displayed correctly but at least you will be able to use the string without having the possibility of mismatching cultures.
toLocaleDateString would be a better solution than toLocaleString for your problem as it doesn't include the time (as you only are requesting the date).
The open-source JavaScript library Date.js has some great methods for formatting dates, as well as it supports a bunch of languages:
Date.js at Google Code: http://code.google.com/p/datejs/
If you want nicely formatted dates / times, you can just pass a formatting string (nearly identical to those used in .NET Framework) into any Date object's .toString() method.
It also has a whole set of cultures which allow you to simply include the appropriate script for that culture.
If you want to manage that yourself (as we do in our apps), you can find resources which give you the list of appropriate resource strings for a given culture. Here's one that shows proper formatting strings for a ton of cultures: http://www.transactor.com/misc/ranges.html
As you are using ASP.NET then you may also be using ASP.NET Ajax. If so, there are two properties on the ScriptManager that are of use to you:
EnableScriptLocalization - Gets or sets a value that indicates whether the ScriptManager control renders localized versions of script files.
EnableScriptGlobalization - Gets or sets a value that indicates whether the ScriptManager control renders script that supports parsing and formatting of culture-specific information.
<asp:ScriptManager ID="AjaxManager" runat="Server" EnablePartialRendering="true"
EnableScriptGlobalization="true" EnableScriptLocalization="true" />
When you enable both of these (set to true) then ASP.NET Ajax extenders etc. should automatically be localised into the culture specified in web.config:
<configuration>
<system.web>
<globalization
fileEncoding="utf-8"
requestEncoding="utf-8"
responseEncoding="utf-8"
culture="en-GB"
uiCulture="en-GB" />
</system.web>
</configuration>
For instance, setting this will localise the AjaxControlToolkit Calendar into your specificed culture.
Even if you are NOT using ASP.NET Ajax adding a ScriptManager and enabling localisation will give you a useful javascript variable called __cultureInfo that contains a JSON array of localised formate, such as currencies, dates etc.
"CalendarType":1,"Eras":[1],"TwoDigitYearMax":2029,"IsReadOnly":true},"DateSeparator":"/","FirstDayOfWeek":1,"CalendarWeekRule":0,"FullDateTimePattern":"dd MMMM yyyy HH:mm:ss","LongDatePattern":"dd MMMM yyyy","LongTimePattern":"HH:mm:ss","MonthDayPattern":"dd MMMM","PMDesignator":"PM","RFC1123Pattern":"ddd, dd MMM yyyy HH\u0027:\u0027mm\u0027:\u0027ss etc....
I solved this problem by using Datejs as
In codebehind(aspx.cs) I get the culture for an employee and add the appropriate js to the header as
string path =
"http://datejs.googlecode.com/svn/trunk/build/date-"
+ GetCulture() + ".js"; Helper.AddJavaScript(this, path);
(in your case you can get the culture from navigator.systemLanguage (or navigator.browserLanguge etc) and add a script tag to the header with src attribute pointing to the appropriate path)
On the client-side I use
d.toString(Date.CultureInfo.formatPatterns.shortDate)
where d is any date object
(I tried using Date.today().toShortDateString() but it was throwing exception. (the CultureInfo JSON object had a different structure than what the function expects).

Resources