I would like to load the ErrorMessage
for my CustomValidator
from a resource file.
I have my CustomValidator
set up like so:
<asp:CustomValidator ID="cv1" runat="server" ControlToValidate="txt1"
ErrorMessage="TEXT TO BE LOCALIZED" OnServerValidate="cv1_Validate" />
And my validation method is as follows:
protected void cv1_Validate(object source, ServerValidateEventArgs e)
{
if (FalseCondition)
{
e.IsValid = false;
}
else
{
e.IsValid = true;
}
}
The validation works correctly, but I would like to have the ErrorMessage
be pulled from my local resources file.
EDIT: I'm also curious if there is any way to do this using meta:resourcekey
.
Assuming you have a local resource for your page (or control), this would be the way to do it
ErrorMessage="<%$ resources:ResourceName %>"
In case you get the text from a global resource file you should do something like this
ErrorMessage="<%$ resources:Strings, ResourceName %>"
Where Strings
is the name of the file. This approach is called explicit localization.
EDIT
You can use meta:resourcekey
. This is called implicit localization. You'll need to have local resources since this approach is not valid for global resources.
Make sure that you have local resource files (.resx files) that meet the following criteria:
They are in an App_LocalResources folder.
The base name matches the page name.
For example, if you are working with the page named Default.aspx, the resource files are named Default.aspx.resx (for the default resources), Default.aspx.es.resx, Default.aspx.es-mx.resx, and so on.
- The resources in the file use the naming convention resourcekey."property".
For example, key name Button1."Text".
In the control markup, add an implicit localization attribute.
For example:
<asp:Button ID="Button1" runat="server" Text="DefaultText" meta:resourcekey="Button1" />
Source: MSDN
If you want to do it in the code-behind, you can use the following:
ResourceManager resmgr = new ResourceManager("YourApplication.YourBaseResourceFile ",
Assembly.GetExecutingAssembly());
protected void cv1_Validate(object source, ServerValidateEventArgs e)
{
if (FalseCondition)
{
CultureInfo ci = Thread.CurrentThread.CurrentCulture;
String str = resmgr.GetString("Error Msg Key in Resource File");
cv1.ErrorMessage =str;
e.IsValid = false;
}
else
{
e.IsValid = true;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With