Limiting length of a phone number - c#

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

Related

When I use & operand in html textarea, it doesn't appear

I have a text area field as shown below, when I enter a string like that : testing123!&aaa it only returns testing123!
<span class="value">
#Html.TextAreaFor(m => m.Nr2FieldComment, 4, 43, new { #class = "" })
</span>
I'm assuming you're having this issue with your ajax request, if true, please use encodeURIComponent like bellow;
var commentClean = encodeURIComponent(comment);
The '&' character has special meaning as the lead character in specifying special character values. Use & instead and it should appear. Lookup all the special character codings to see how and when you need this notation.

ASP.NET MVC & C# : better Dollars and Cents data entry

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.

Why doesn't my Input of type=number show a decimal when used with ASP.NET MVC?

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/

ASP.NET MVC converting a model list of string with spaces into a javascript array

I'm using ASP.NET MVC (with Razor) and JQuery
I have a list of strings in my controller and I render the partial view passing in the model with the below list.
List<string> list = new List<string>();
list.Add("Texas");
list.Add("New York");
On client in my cshtml file side I have:
<div id = "test", test-att = #Html.Raw(Json.Encode(Model.list)) />
In my javascript file I do:
var javascriptArray = JSON.parse($('#test').attr('test-att'));
I get an error "unexpected end of input".
Using Chrome dev tools console I see the following:
$('#test') : <div id ="test" test-att = "["Texas", "New" York"]>
$('#test').attr('test-att') : "["Texas","New"
I'm expecting : "["Texas","New York"]"
Looking like its getting messed up because of the space before being passed in JSON.parse. It seems to stop when it finds a space.
Any ideas on how to fix this?
Put your JSON between single quote NOT double quote characters:
<div id = "test" test-att = '#Html.Raw(Json.Encode(Model.list))' />
Content of cshtml file will be like as bellow
<div id = "test" test-att = "#Html.Raw(Json.Encode(Model.list))" />
There seems to be 2 issues with what you have :
The Json encoder uses " (double quotes) to delimitate strings. It's not gonna work since in XML double quote are used to delimitate attributes.
For this issue you have 2 solutions the easiest one would probably be replacing every " in the Json Encoded string by
<div id = "test", test-att ="#Html.Raw(Json.Encode(Model.list).Replace("\"",""")" />
It seems to me the culprit is #Html.Raw. If you use the following -
<div id='dd' data-att="#Json.Encode(list)">
Then parsing with javascript doesn't fail.
var a = document.getElementById('dd');
JSON.parse(a.dataset.att);
Single quote or double quote doesn't matter. But if you use #Html.Raw then double quote gives you the said error. You can use #Html.Raw against each item of your list instead -
<div id='dd' data-att="#Json.Encode(list.Select(x=> Html.Raw(x).ToHtmlString()).ToList<string>())">
This will work with double quote.

Razor - how to get n number characters of string?

I have an asp.net mvc 4 application with the following
Model
public string Price {get;set;}
it saves in database a string, eg. "41.99".
View
#foreach(var item in Model)
{
<div class="price">#item.Price</div>
}
it returns the value "41.99" all good here.
however I would like to pick the values differently.
Below is the Html output for what I need
#foreach(var item in Model)
{
<div class="price">
<span class="dollar">41</span>
<span class="cents">99</span>
</div>
}
Please Note that the value is split in 2 parts and the dot is left out.
The string will be inserted on input field as money, so it need to be inserted as "41.99"
Other consideration is if the value before the dot are 1, 11, 111, 1111 characters, it need display all numbers.
So how could I archive this?
#foreach(var item in Model)
{
<div class="price">
<span class="dollar">#item.Price(first part)</span>
<span class="cents">#item.Price(second part)</span>
</div>
}
Any help or guindance would be apprecciated.
If your data is string then
var price = "41.99";
var parts = price.Split('.');
var dollar = parts[0];
var cents = parts[1];
If your data is decimal
decimal price = 41.99m;
var dollar = (int)price;
var cents = (int)((price % 1) * 100);
Setting aside the fact you should not be using string to represent numerical values and use decimal instead for money values... and the fact that . is not the only separator (depending on locale)...
String.Split is the easiest way to split the string on a separator:
var parts = item.Price.Split(`.`);
Now you have parts[0] with "dollar" value, and need to deal with fractional part which may or may not be there. Note that you may need to pad cents value if you need something like 04 instead of just 4
#{
var parts = #item.Price.Split('.');
var cents = (parts.Length == 2) ? cents = parts[1] : "0";
}
<span class="dollar">#parts[0]</span>
<span class="cents">#cents</span>
Thanks for all replies
I figured it out combining the answers here with some suggestions.
here is the answer for my question:
Model:
public double Price { get; set; }
Controller:
public ActionResult Details(int id)
{
var data = _Context.Products.Where(d => d.ProductId == id).First();
if (data == null)
{
return HttpNotFound();
}
return View(data);
}
In View:
string s = Model.Price.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture);
string[] parts = s.Split('.');
int i1 = int.Parse(parts[0]);
int i2 = int.Parse(parts[1]);
<span>#i1</span>
<span class="decimal">#i2</span>
Works like a charm
Thanks a lot

Categories

Resources