Is there a way to get an ASP.NET textbox to accept only currency values, and when the control is validated, insert a $ sign beforehand?
Examples:
10.23 becomes $10.23
$1.45 stays $1.45
10.a raises error due to not being a valid number
I have a RegularExpressionValidator that is verifying the number is valid, but I don't know how to force the $ sign into the text. I suspect JavaScript might work, but was wondering if there was another way to do this.
The ASP.NET MaskedEdit control from the AJAX Control Toolkit can accomplish what you're asking for.
I know an answer has already been accepted, but I wanted to throw out another solution for anyone with the same problem and looking for multiple workarounds.
The way I do this is to use jQuery format currency plugin to bind user input on the client side. Parsing this input on the server side only requires:
// directive
using System.Globalization;
// code
decimal input = -1;
if (decimal.TryParse(txtUserInput.Text, NumberStyles.Currency,
CultureInfo.InvariantCulture, out input))
{
parameter = input.ToString();
}
The only downfall to this is that the user can have javascript turned off, in which case the RegEx validator running server-side would work as a fall-back. If the control is databound, all you have to do is decimalValue.ToString("{0:c}") , as mentioned by others, in order to display the proper currency formatting.
The cool thing about this is that if the user enters the textbox and it shows $0.00 on the client side, the server-side if statement would return false. If your decimal value isn't nullable in the database, just change decimal input = -1 to decimal input = 0 and you'll have a default value of 0.
Another way to do this might be to place the dollar sign outside to the left of the text box. Is there a real need to have the dollar sign inside of the box or will a simple label do?
decimal sValue = decimal.Parse(txtboxValue.Text.Trim());
// Put Code to check whether the $ sign already exist or not.
//Try making a function returning boolean
//if Dollar sign not available do this
{ string LableText = string.Format("{0:c}", sValue); }
else
{ string LableText = Convert.ToString(sValue); }
string sValue = Convert.ToString(txtboxValue.Text.Trim());
// Put Code to check whether the $ sign already exist or not.
//Try making a function returning boolean
//if Dollar sign not available do this
{ string LableText = string.Format("{0:c}", "sValue"); }
else
{ string LableText = Convert.ToString(sValue); }
In the .CS you could do a pattern match along the lines of,
string value = text_box_to_validate.Text;
string myPattern = #"^\$(\d{1,3},?(\d{3},?)*\d{3}(\.\d{0,2})|\d{1,3}(\.\d{2})|\.\d{2})$";
Regex r = new Regex(myPattern);
Match m = r.Match(value);
if (m.Success)
{
//do something -- everything passed
}
else
{
//did not match
//could check if number is good, but is just missing $ in front
}
Related
So I created a Razor page with a #html.textboxfor that I want to allow only numbers. I changed the type to number, but still, when testing it, it will accept comma and point. I tried some onchange functions to get the value from that textbox, replace all commas or points with nothing, and return to the same textbox. I managed to do that using a second textbox just for testing, but I don't want that behavior. I want the textboxfor to have the same behavior as when I try to type any letters. Which means, do nothing. I just started learning C#/Asp.net, and I couldn't find anything on google. Maybe I'm not searching for the right names, so any tips or directions on what I should research for would be greatly appreciated.
I actually found something that works perfectly. Just in case anyone wants to use it.
First I created the TextboxFor and removed the number type:
#Html.TextBoxFor(i => i.price, new { #id = "amount", #onInput = "javascript: replaceComma('amount'); "})
Then I added this javascript to replace any non-number char with an empty value:
<script type="text/javascript">
function replaceComma(i) {
var val = document.getElementById(i).value;
val = val.replace(/[^0-9]+/g, '')
document.getElementById(i).value = val;
}
</script>
I'm not sure this is the best approach, but it seems to be working now.
i have question about query string in asp.net:
standart query string with query string parameter is "www.mysity.url?key1=value1&key2=value2", but i need only check has query string key or not...yes, one of the correct decisions: www.mysite.url?reset=true, but this excess syntax for me.
in markup i use something like "<a href='UrlHelper.GetResetUrl()'>Reset</a>", this method return "www.mysity.url?reset", but in user side markup i have "Reset"
If you do not specify the name for a parameter it is taken as null.
Its value would be reset
So you would have to check it as follows:
if(Request.QueryString[null]=="reset")
{
//Take some reset action
}
a Quick and dirty solution is:
if(Request.Url.Query.Contains("?reset"))
{
// ok we have a reset
}
Assuming that you have a standard reset call ask as: www.mysity.url?reset and the reset url not have other parameters. If you have you can simple check for the reset keyword.
This code HttpContext.Current.Request["reset"] is always return null, so the next best thing if you like to make it hard, is to manual analyze your keys after the url.
All code that handles querystring parameters should be case insensitive. Browsers (or parts of internet infrastructure?) may convert the case.
One way to check if reset parameter is present in querystring:
bool reset = Request.Url.Query.IndexOf("reset", StringComparison.CurrentCultureIgnoreCase) > -1;
I've just moved to web development and need to know how i can implement below requirement using asp.net and vb.net.
I have three fields in a form which are filled by users. Based on these three values, i need to auto-populate the 4th field. I have planned to implement this in the following way
Write a separate class file with a function to calculate the possible values for the 4th fields based on 1st 3 inputs. This function can return some where between 1-10 values. So I've decided to use drop-down for 4th field, and allow users to select the appropriate value.
Call the above function in onchange function of 3rd field and take and use the return values to populate the 4th field. I'm planning to get the return values in array field.(Does this need a post back?)
Please let me know how if there is better way to implement this.
Thanks.
You may want to consider doing this with Javascript. You could read and control the fields pretty easily with pure Javascript, or using a nice library like jQuery (my favorite). If you did it this way, no post-back would be required and the 4th field would update immediately. (Nice for your users)
You can also do it with ASP.NET for the most part. "onchange" in ASP.NET still requires Javascript as far as I know, it just does some of it for you. A post-back will definitely happen when you change something.
You need javascript or to set autopostback=true on your form elements.
From a user perspective the best thing is to use javascript to populate the field for display, BUT when the form is submitted use your backend function to validate it. This will make sure the user didn't change the value.
An easy way is to use jQuery for the UI (that way you don't have to worry about long winded javascript and deal with browser compatibility as it's already taken care of for you) and have it call to the server for the data. For the server, your easiest route is to return JSON for looping values.
Include your jQuery:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
Then add in a handle for the JavaScript:
<script type="text/javascript">
function autoPopulate() {
var value1 = $('#ddl1').val();
var value2 = $('#ddl2').val();
var value3 = $('#ddl3').val();
var url = 'path/to/your/file.aspx?value1=' + value1 + '&value2=' + value2 + '&value3=' + value3;
$.getJSON(url, function(data) {
data == null ? return false : data = eval(data);
var ddl = $('#ddl4')[0];
for (i = 0; i < data.length; i++) {
var option = new Option(data[i][0], data[i][1]);
if ($.browser.msie) {
ddl.add(option);
} else {
ddl.add(option, null);
}
}
}
}
</script>
(Yes, I know I used a native loop but I'm little lazy here today :) )
Now, for your server side code you'll want your code your page to return data in the format of:
[['value1','text1'],['value2','text2'],['value3','value3']]
so something like:
<script type="vb" runat="server">
Private Sub Page_Init()
// get your data
// loop through it and add in values
// ex.
Dim result As String = "[" //start multi-dimensional array
For Each Item As String In data
result += String.Format("['{0}','{1}'],", _value, _text)
Next
result = result.SubString(0, result.Length - 1) // removes trailing comma
result += "]" // closes off m-array
Response.Write(result)
Response.Flush()
End Sub
</script>
Hii,
I have a query string like "http://project/page1.aspx?userID=5". The operation won't be performed, if the 'userID' parameter changed manually. How it is possible?
Hii all, thank you for your assistance... and i got some difference sort of solution from some other sites. i don't know that the best solution. that is to encode the value using an encryption and decryption algorithm... The sample code has been written like this...
<a href='Page1.aspx?UserID=<%= HttpUtility.UrlEncode(TamperProofStringEncode("5","F44fggjj")) %>'>
Click Here</a> <!--Created one anchor tag and call the function for TamperProofStringEncode-->
private string TamperProofStringEncode(string value, string key)
{
System.Security.Cryptography.MACTripleDES mac3des = new System.Security.Cryptography.MACTripleDES();
System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
mac3des.Key = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(key));
return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(value)) + "-" + Convert.ToBase64String(mac3des.ComputeHash(System.Text.Encoding.UTF8.GetBytes(value)));
}
In the page load of 'Page1' call the decode algorithm to decode the query string
try
{
string DataString = TamperProofStringDecode(Request.QueryString["UserID"], "F44fggjj");
Response.Write(DataString);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
private string TamperProofStringDecode(string value, string key)
{
string dataValue = "";
string calcHash = "";
string storedHash = "";
System.Security.Cryptography.MACTripleDES mac3des = new System.Security.Cryptography.MACTripleDES();
System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
mac3des.Key = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(key));
try
{
dataValue = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(value.Split('-')[0]));
storedHash = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(value.Split('-')[1]));
calcHash = System.Text.Encoding.UTF8.GetString(mac3des.ComputeHash(System.Text.Encoding.UTF8.GetBytes(dataValue)));
if (storedHash != calcHash)
{
//'Data was corrupted
throw new ArgumentException("Hash value does not match");
// 'This error is immediately caught below
}
}
catch (Exception ex)
{
throw new ArgumentException("Invalid TamperProofString");
}
return dataValue;
}
It sounds like a strange requirement. Are you trying to implement some sort of home-grown security? If it's so, you really shouldn't.
Anyway, one way you could do it would be to take the entire url http://project/page1.aspx?userID=5 and calculate its md5 sum. Then you append the md5 sum to the final url, such as http://project/page1.aspx?userID=5&checksum=YOURCALCULATEDMD5SUM. Then in page1.aspx you will have to validate that the checksum parameter is correct.
However, this approach is quite naïve and it would not necesarily take very long for anyone to figure out the algorithm you have used. If they did they could "easily" change the userid and calculate an md5 sum themselves. A more robust approach would be one where the checksum was encrypted by a key that only you had access to. But again I have to question your motive for wanting to do this, because other security solutions exist that are much better.
Here is another option that I found incredibly useful for my requirements:
4 Guys From Rolla - Passing Tamper-Proof QueryString Parameters
You can't.
Anything in the HTTP request (including URL, query string, cookies, ...) is under the control of the client and is easy to fake.
This is why it is important to whitelist valid content, because the client can arbitrarily add anything it likes in addition to what you you prompt to receive.
My favourite is the following. It uses a HTTPmodule to transparently encode and decode the Querystring with the explicit purpose of preventing tamperring of the querystring.
http://www.mvps.org/emorcillo/en/code/aspnet/qse.shtml
It is perfect when Session is not an option!
You can't tell whether it has been changed manually. If you use query strings then you hyave to make sure that it doesn't matter if it is changed. e.g. if you are using it to show a user their account details, you need to check wether the selected user, is the current user and show an error message instead of user data if it is not.
If the user is allowed to change record 5, but not record 7 for example, this has to be enforced server-side. To do this you need to be able to identify the user, by requiring a login, and giving them a unique session key that is stored in their browser cookie, or as another parameter in the url query string.
There are abundant packages/modules/libraries in man languages for dealing with authentication and sessions in a sensible way - roll you own at your own peril :)
Well - it depends :)
One possibility is to put the userID into a session variable. So the user cannot see or edit the value.
If you have other means to detect if the value is invalid (i.e. does not exist or cannot be for that user (who you can identify through some other way) or the like) you might get away with validating the input yourself in code behind.
But as you probably know you cannot prevent the user changing the query string.
I have an ASP.NET web form where I can can enter an email address.
I need to validate that field with acceptable email addresses ONLY in the below pattern:
xxx#home.co.uk
xxx#home.com
xxx#homegroup.com
A regular expression to validate this would be:
^[A-Z0-9._%+-]+((#home\.co\.uk)|(#home\.com)|(#homegroup\.com))$
C# sample:
string emailAddress = "jim#home.com";
string pattern = #"^[A-Z0-9._%+-]+((#home\.co\.uk)|(#home\.com)|(#homegroup\.com))$";
if (Regex.IsMatch(emailAddress, pattern, RegexOptions.IgnoreCase))
{
// email address is valid
}
VB sample:
Dim emailAddress As String = "jim#home.com"
Dim pattern As String = "^[A-Z0-9._%+-]+((#home\.co\.uk)|(#home\.com)|(#homegroup\.com))$";
If Regex.IsMatch(emailAddress, pattern, RegexOptions.IgnoreCase) Then
' email address is valid
End If
Here's how I would do the validation using System.Net.Mail.MailAddress:
bool valid = true;
try
{
MailAddress address = new MailAddress(email);
}
catch(FormatException)
{
valid = false;
}
if(!(email.EndsWith("#home.co.uk") ||
email.EndsWith("#home.com") ||
email.EndsWith("#homegroup.com")))
{
valid = false;
}
return valid;
MailAddress first validates that it is a valid email address. Then the rest validates that it ends with the destinations you require. To me, this is simpler for everyone to understand than some clumsy-looking regex. It may not be as performant as a regex would be, but it doesn't sound like you're validating a bunch of them in a loop ... just one at a time on a web page
Depending on what version of ASP.NET your are using you can use one of the Form Validation controls in your toolbox under 'Validation.' This is probably preferable to setting up your own logic after a postback. There are several types that you can drag to your form and associate with controls, and you can customize the error messages and positioning as well.
There are several types that can make it a required field or make sure its within a certain range, but you probably want the Regular Expression validator. You can use one of the expressions already shown or I think Visual Studio might supply a sample email address one.
You could use a regular expression.
See e.g. here:
http://tim.oreilly.com/pub/a/oreilly/windows/news/csharp_0101.html
Here is the official regex from RFC 2822, which will match any proper email address:
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
I second the use of a regex, however Patrick's regex won't work (wrong alternation). Try:
[A-Z0-9._%+-]+#home(\.co\.uk|(group)?\.com)
And don't forget to escape backslashes in a string that you use in source code, depending on the language used.
"[A-Z0-9._%+-]+#home(\\.co\\.uk|(group)?\\.com)"
Try this:
Regex matcher = new Regex(#"([a-zA-Z0-9_\-\.]+)\#((home\.co\.uk)|(home\.com)|(homegroup\.com))");
if(matcher.IsMatch(theEmailAddressToCheck))
{
//Allow it
}
else
{
//Don't allow it
}
You'll need to add the Regex namespace to your class too:
using System.Text.RegularExpressions;
Use a <asp:RegularExpressionValidator ../> with the regular expression in the ValidateExpression property.
An extension method to do this would be:
public static bool ValidEmail(this string email)
{
var emailregex = new Regex(#"[A-Za-z0-9._%-]+(#home\.co\.uk$)|(#home\.com$)|(#homegroup\.com$)");
var match = emailregex.Match(email);
return match.Success;
}
Patricks' answer seems pretty well worked out but has a few flaws.
You do want to group parts of the regex but don't want to capture them. Therefore you'll need to use non-capturing parenthesis.
The alternation is partly wrong.
It does not test if this was part of the string or the entire string
It uses Regex.Match instead of Regex.IsMatch.
A better solution in C# would be:
string emailAddress = "someone#home.co.uk";
if (Regex.IsMatch(emailAddress, #"^[A-Z0-9._%+-]+#home(?:\.co\.uk|(?:group)?\.com)$", RegexOptions.IgnoreCase))
{
// email address is valid
}
Of course to be completely sure that all email addresses pass you can use a more thorough expression:
string emailAddress = "someone#home.co.uk";
if (Regex.IsMatch(emailAddress, #"^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#home(?:\.co\.uk|(?:group)?\.com)$", RegexOptions.IgnoreCase))
{
// email address is valid
}