Is there a way to better control the user experience of Html.TextBoxFor?
I currently have:
#Html.TextBoxFor(m => m.TotalDue,
new { #id = "TotalDue", #class = "decimal_input", #dir = "rtl" })
And a model of:
public decimal TotalDue { get; set; }
When a user comes to that field, if a 0 is displayed and the user begins to type his/her dollar amount, the leading zero stays there. When the user leaves the field, the amount is not formatted.
Ideally, I would like the user to come to the field and if they typed 123456.78 and then pressed TAB to the next field, it would display 123,456.78. If they type 123456, it would display 123,456.00. It would be best if it formatted as they typed, although I could live with just making the field pretty when they leave the field.
I have experimented with Html.EditorFor, but haven't found the right combination. I am open to using that or a "helper" of some sort. I would like the user to have the same experience as found in PDF forms, or something close to it.
Try this: imask.js. I've done a jsfiddle to demonstrate here, and a .NET fiddle here.
Include <script src="https://unpkg.com/imask"></script> on your page and then this script:
var totalDueMask = IMask(
document.getElementById('TotalDue'),
{
mask: '$num',
blocks: {
num: {
mask: Number,
radix: '.',
thousandsSeparator: ','
}
}
}
);
I've formatted it for USD but you can adjust the settings to suit - all the options are documented on the IMask site.
Related
I'm trying to use a input number in MVC, it accepts correctly the comma (I'm in a culture with a comma as a decimal separator) and MVC accepts it with the custom binder I made. The value is correctly saving in database, and comes back.
The problem is, when passing the decimal value, which looks like 0.231 to the number control, I guess it tries to format it to my culture with a comma and doesn't work, so nothing appears.
The binder works on return to server, but do I need something else on the return to the control for it to work on the return to the page?
My control in the razor view:
#Html.EditorFor(model => model.DecimalValueForExample, new { htmlAttributes = new { #class = "form-control", #type = "number", #step = "any", #min = "0.001", autocomplete = "off" } })
My attribute in the viewmodel:
[Display(Name = "DecimalValueForExample", ResourceType = typeof(Properties.Resources))]
[DisplayFormat(DataFormatString = "{0:0.###}", ApplyFormatInEditMode = true)]
[Range(0.001, double.MaxValue, ErrorMessageResourceName = "RangeErrorMessage", ErrorMessageResourceType = typeof(Properties.Resources))]
[Required]
public decimal DecimalValueForExample{ get; set; }
This has been a browser compliance issue in the past and the levels of support varies between browsers and the OS.
The last chart I have found is about 12 versions behind on Chrome, which at the time did not support commas on Windows.
HTML5 number inputs – Comma and period as decimal marks
There were some JS workarounds that have appeared hear as well,
html tag input of type=”number” and culture based decimal separator
Nothing worked, especially across multiple browser. So the answer was to use a spinner control, I use http://www.virtuosoft.eu/code/bootstrap-touchspin/
I want a field for a phone number to take in a maximum of 10 digits. I have the [stringlength] attribute placed but I still cannot get the desired result. Thanks to those that can help me.
On a side note, is it possible to break apart the phone number so that the area code and the remaining digits get sent out separately to a db via a stored proc?
model:
public class Pharmacy
{
[StringLength(10,MinimumLength=10)]
public string PhoneNumber
{
get
{
return _phoneNumber;
}
set
{
Regex regexObj = new Regex(#"[^\d]");
_phoneNumber = regexObj.Replace(value, "");
_phoneNumber = Regex.Replace(_phoneNumber, #"(\d{3})(\d{3})(\d{4})", "($1) $2-$3");
}
}
}
form field:
<label id="lblPhoneNumber">Phone Number</label>
<input style="margin: 5px; " type=text name="txtPhoneNumber" id="txtPhoneNumber" value="#Model.Pharmacy.PhoneNumber" />
Why are you using HTML tags for the input if you're using ASP.NET MVC? You should really use Razor tags.
#Html.LabelFor(model => model.PhoneNumber, new { id = "lblPhoneNumber" })
#Html.TextBoxFor(model => model.PhoneNumber, new { id = "txtPhoneNumber", style="margin: 5px;", name="txtPhoneNumber", #Value = Model.Pharmacy.PhoneNumber })
#Html.ValidationFor(model => model.PhoneNumber, "", new { #class = "text-danger" })
Also, make sure you have unobtrusiveJS NuGet UnobtrusiveJS for the validation. Everything else seems fine with the data annotation. The unnamed parameter of [StringLength] is the maximum length, while you need to specify a minimum length. You might also want to let the user know about the error, so you'll need an error message as well [StringLength(10, MinimumLength=10, ErrorMessage="* Must be 10 digits")]
For the second part of the question
On a side note, is it possible to break apart the phone number so that the area code and the remaining digits get sent out separately to a db via a stored proc?
Yes, use RegEx capture groups, which you're already doing :).
RegEx regEx = new Regex(#"(\d{3})(\d{3})(\d{4})")
Matches matches = regex.Matches(value);
// matches[0] contains area code
// matches[1] contains first 3 digits
// matches[2] contains final 4 digits
MSDN - Regex.Matches
How can I properly validate a price field when doing postback?
I have already checked: How can I validate a currency field? but that doesn't fulfil my expectations.
I've tried with (and some variations):
[Range(0, (double)decimal.MaxValue)]
[DataType(DataType.Currency, ErrorMessage = "...")]
public decimal? Price {get; set;}
Problems:
It never uses the [DataType...] attribute to perform validations.
When the value used is not of decimal type, the issued validation error will be a standard English message that I don't know how to customize and need to.
If I make it string instead of decimal?, then the range validation will be thrown for non-decimal or negative values, but it will still allow values like: 1.23456, which is not the currency format I'm expecting.
I'm looking for a built-in approach before I have to create my own custom validation or regular expression. Something like:
[EmailAddress()]
public string ContactEmail {get; set; }
This perfectly suits me!
You can use FluentValidation. You create your own validator class inheriting from : AbstractValidator and inside the constructor you can put all your logic.
MyCurrencyValidatorMyClass : AbstractValidator<MyClass>
{
MyCurrencyValidatorMyClass()
{
RuleFor(x => x.MyField).NotNull().GreatherThan(0);
//All your rules
}
}
var validator = new MyCurrencyValidatorMyClass();
var myClassVar = new MyClass();
validator.Validate(myClassVar);
Also you can integrate your validator with MVC, for reference please see
https://fluentvalidation.codeplex.com/wikipage?title=mvc
For decimal reference see
https://github.com/JeremySkinner/FluentValidation/blob/master/src/FluentValidation/Validators/ScalePrecisionValidator.cs
This is the nuget package https://www.nuget.org/packages/FluentValidation
You can try this RegEx on your Price model property. It will check for strings in the format of "XXXX.XX" where X is a numeric digit (0-9):
[RegularExpression(#"\d{1,20}(\.\d{1,2})?", ErrorMessage = "Invalid Price. Please use the format of XXXX.XX.")]
The first range d{1, 20} allows up to twenty digits before the decimal place. The second range d{1, 2} allows up to two decimal places.
Haven't been able to find a good answer to my situation yet. I want this textbox to only take numbers and still have the id "SearchString2" so I can use it in my controller. Any idea how?
if (Roles.IsUserInRole(WebSecurity.CurrentUserName, "Admin"))
{
#:<p><b>Customer ID:</b> #Html.TextBox("SearchString2")</p>
}
Thanks in advance.
You can do something like this:
#Html.TextBox('SearchString2', new { #type = "number" })
This should set the type to be a number, you could then use attributes on your model to help limit it to only ints like so:
[RegularExpression(#"^[A-Z]+[a-zA-Z''-'\s]*$")]
[Required]
public string SearchString2 { get; set; }
You'll need to replace the regex with an actual regex and put an validation message in.
Here's more info on validation: http://www.asp.net/mvc/overview/getting-started/introduction/adding-validation
Actually, I think the correction needed to the above answer is
#Html.TextBox('SearchString2',null, new {#type="number"})
otherwise type=number shows up in the value.
I am hoping there is a solution to this,
I have an example MVC application, and I want to output formatted snippets of code to the browser
Something like the following
ViewBag.PageSource = "
public class RegisterViewModel
{
[Required]
[Display(Name = "User name")]
[RegularExpression("[a-zA-Z0-9]{2,64}", ErrorMessage = "username must contain letters or numbers only, and be between 2 and 64 characters long ")]
public string UserName { get; set; }
}
";
Is this sort of thing possible ?
I have a modal popup in the main layout file and I wanted this to contain the source (model/controller) snippets for each view, by placing it in a viewbag variable in each view
Don't try to do this at the controller. That's what the view is for.
code.google.com & Stackoverflow use Code-Prettify.
You can then use it with the pre tags:
<pre class="prettyprint">
public class RegisterViewModel<br/>
{<br/>
[Required]<br/>
[Display(Name = "User name")]<br/>
[RegularExpression("[a-zA-Z0-9]{2,64}", ErrorMessage = "username must contain letters or numbers only, and be between 2 and 64 characters long ")]<br/>
public string UserName { get; set; }<br/>
<br/>
}<br/>
</pre>
Yes, anything is possible. Add the # sign in front of first " and multi-line strings will work.
Then you need to do something about the tabs. You could use <pre> tag or replace tabs with a fixed-width div.
If snippet is dynamicly generated you have to use JavaScript formatted.
For example
SyntaxHighlighter is good client-side solution:
http://alexgorbatchev.com/SyntaxHighlighter/
In other case take a look here
Jon Skeet provides a code formatter for public use:
http://csharpindepth.com/CodeFormatterTool.aspx
UPDATE
Seems to me that SO use this https://code.google.com/p/google-code-prettify/
For HTML5 you should use <pre><code>//your code here</code></pre>.