Decimal value with 4 decimal place in TextBoxFor in ASP MVC - validation

Need help adding validation on textbox field where the datatype of textbox is decimal and it can have max length of 15 digits or max length of 15 with 4 decimal places.
Example:
1234
123456789012345
123456789012345.1234
This is how part of the code looks like:
public decimal ShipmentWeight { get; set; }
Razor:
#Html.TextBoxFor(model => model.ShipmentWeight, new {#class = "form-control"})
#Html.ValidationMessageFor(model => model.ShipmentWeight)
Does anyone know how i can achieve this?
Thanks.

Related

How to validate textbox in MVC3 that must contain string started with characters "PR"

i am very much new to MVC3 and working with MVC3 razor application. I need to validate a textbox on View in such a way that, the textbox will accept only those strings which are starting with characters "PR" and 4th character of that string must be "2". It would be great if anybody helps me. Thanks in advance
Well you need regex. I'm not exactly sure what the regex would be and what your string contains. But if you need to have 2 matches in there, you could split it and use 2 textboxes and join the values on post.
ViewModel:
public class MyViewModel
{
[RegularExpression("^PR[A-Za-z0-9]", ErrorMessage= "Invalid Text1")]
public string MyText1 { get; set; }
[RegularExpression("^2[A-Za-z0-9]", ErrorMessage= "Invalid Text2")]
public string MyText2 { get; set; }
}
Warning, this regex may be faulty. I invite others to edit/post comments and i can update it with correct regex
View:
#model MyProject.Models.MyViewModel
#using (Html.BeginForm())
{
#Html.TextBoxFor(m => m.MyText1)
#Html.TextBoxFor(m => m.MyText2)
<button type="submit">Submit</button>
}
Hope this helps
Model
public class RegisterModel
{
public int ID { get; set; }
[RegularExpression(#"^PR[a-zA-Z0-9]2([a-zA-Z0-9]*)$", ErrorMessage = "Please enter valid Name.")]
[Required(ErrorMessage = "Name is required.")]
public string Name { get; set; }
}
View
#using (Html.BeginForm("DYmanicControllerPage", "Test", FormMethod.Post, new { id = "FrmIndex" }))
{
<div>
#Html.LabelFor(m => m.Name)
#Html.TextBoxFor(m => m.Name)
#Html.ValidationMessageFor(m => m.Name)
</div>
}

RegEx for decimal puts 0 (zero) in the text field

I am trying the following RegEx to validate the decimal value like
[RegularExpression("^(?:\\d{1,100000000}(?:\\.\\d{0,6})?)?$")]
[Range(double.MinValue,double.MaxValue)]
public decimal Amount { get; set; }
rendering in the view like
<div class="editor-field">
<%:Html.TextBoxFor(x=>x.Amount)%>
<%:Html.ValidationMessageFor(x=>x.Amount) %>
</div>
the problem is it puts a 0 in the textbox by default, please guide me find out the problem, also if there is a better way to validate the decimal field please do mention...
Try settings the type of your Amount property to nullable:
public decimal? Amount { get; set; }

Date picker in mvc3 with razor view engine without using jquery

I am new to mvc3 and i am using c# coding and razor my view engine. Is there any way to use date picker with out using jquery and something else.
If you don't use javascript and jquery, well, you are left with HTML. And you know that in HTML you have standard input fields such as <input type="text">. Using pure HTML you cannot make a dynamic datepicker show when the user clicks on some date input.
Well, if you want to avoid "all scripting languages" I suppose you should have three dropdowns,
Months (1 - 12)
Days (1 - 31)
Years
Your Model would need to take three seperate fields for Month, Day and Year. Then in your controller action you will need to do some Date parsing to make sure it is a valid date and if not, add a ModelState Exception.
Since MVC comes with jQuery (and the validators are very helpful), why are you trying to avoid using them?
All of it COULD be done with jQuery or even plain JavaScript so you're really limiting yourself.
EDIT - Adding code sample
Your Model
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
public class DatePickerViewModel
{
[Required]
[DisplayName("Month")]
[Range(1,12,ErrorMessage = "Month must be between 1 and 12")]
public int? Date_Month {get;set;}
[Required]
[DisplayName("Day")]
[Range(1,31,ErrorMessage = "Day must be between 1 and 31")]
public int? Date_Day {get;set;}
[Required]
[DisplayName("Day")]
[Range(1900,2012,ErrorMessage = "Year must be between 1900 and 2012")]
public int? Date_Year {get;set;}
}
Your controller
public class DatePickerController : Controller
{
[HttpGet]
public ActionResult Choose()
{
return View(new DatePickerViewModel());
}
[HttpPost]
public ActionResult Choose(DatePickerViewModel model)
{
if(!ModelState.IsValid)
return View(model);
else
{
DateTime date;
if(!DateTime.TryParse(String.Format("{0}/{1}/{2}",model.Date_Month, model.Date_Day, model.Date_Year),out dt))
{
ModelState.AddModelError("","Invalid Date");
return View(model);
}
//Do something with the variable "date"
return View("SomeOtherView");
}
}
}
And your view
#model DatePickerViewModel
#using(Html.BeginForm())
{
<div>
<div>#Html.LabelFor(m => m.Date_Month) #Html.ValidationMessageFor( m => m.Date_Month)</div>
<div>#Html.DropDownListFor(m => m.Date_Month, (from n in Enumerable.Range(0, 12) select new SelectListItem{ Text = n==0? "":n.ToString(),Value = n ==0? "":n.ToString()})</div>
</div>
<div>
<div>#Html.LabelFor(m => m.Date_Day) #Html.ValidationMessageFor( m => m.Date_Day)</div>
<div>#Html.DropDownListFor(m => m.Date_Day, (from n in Enumerable.Range(0, 31) select new SelectListItem{ Text = n==0? "":n.ToString(),Value = n ==0? "":n.ToString()})</div>
</div>
<div>
<div>#Html.LabelFor(m => m.Date_Year) #Html.ValidationMessageFor( m => m.Date_Year)</div>
<div>#Html.DropDownListFor(m => m.Date_Year, (from n in Enumerable.Range(1899, 2012) select new SelectListItem{ Text = n==1899? "":n.ToString(),Value = n == 1899? "":n.ToString()})</div>
</div>
<div><input type="submit" value="Submit"/></div>
}
As you can see, the amound of raw code you need to create just to enable a date selector without using JavaScript at all is pretty large. Considering if you were to just use ANY jQuery date picker all you would need is a nullable DateTime property on your Model/ViewModel, a textbox on your view and a small snippet of JS to turn the text box in to a date selector.
Avoid re-inventing the wheel and reuse code that is already out there for how to use any jQuery Date Picker plugin.

mvc 3 view data validation

i'm trying to put DropDownList validation to work.
in model:
[Required(ErrorMessage = "this field is required")]
public int ObjectTypeID { get; set; }
in view:
<div class="editor-field">
#Html.DropDownList("ObjectTypeID", string.Empty)
#Html.ValidationMessageFor(model => model.ObjectTypeID)
</div>
if the user leaves the selection empty i expect client side validation to alarm. but this does not happen.
what can be done?
The behavior of system types is that they must have a value when initalized. An integer has a value of "0". Change your model to accept a nullable int:
public int? ObjectTypeID { get; set; }
Just wondering, but why not use DropDownListFor?
For client side validation to work I think you need to turn on ClientValidationEnabled & UnobtrusiveJavaScriptEnabled in the web.config for your project, I believe you also need to reference the jquery.validate.unobtrusive.min.js script on your page?
1) You are not loading your dropdownlist
2) Use DropDownListFor in order to match validation with ddl

MVC3 - 3 decimal places on type double with leading zero

I have a field for weight in Kgs (type double or use something else??).
In edit view I would like the user to enter numbers to the thousandth place.
In display view I would like the Kgs to appear like 560.250
Trying to learn MVC3 + Razor.
Willing to explore JQuery, use of regular expressions, validators, view templates, view models...
The "magic" of MVC based on conventions takes getting used to. Confused as to which approach to use.
Thank you in advance for your help.
You could use data annotations on your view model:
[DisplayFormat(DataFormatString = "{0:#,##0.000#}", ApplyFormatInEditMode = true)]
public double? Weight { get; set; }
and in your view
#Html.EditorFor(x => x.Weight)
will properly format the value in the input field.
Another possibility is to write a custom editor template for the double type (~/Views/Shared/EditorTemplates/double.cshtml):
#model double?
#Html.TextBox("", Model.HasValue ? Model.Value.ToString("#,##0.000#") : "")
and then in your view:
#Html.EditorFor(x => x.Weight)
or if you don't want to override all templates for all double types in your application you could put this into some custom template location like ~/Views/Shared/EditorTemplates/MyFormattedDouble.cshtml and then in your view:
#Html.EditorFor(x => x.Weight, "MyFormattedDouble")
Personally I prefer the first approach which uses data annotations to control the format of the double values.
To format the number just use
#string.Format("{0:0.00}", Model.Weight);
or
#Html.DisplayFor(x => string.Format("{0:0.00}", x.Weight));
#Html.EditorFor(x => string.Format("{0:0.00}", x.Weight));
to Validate
public class Model
{
[Required]
public double Weight{ get; set; }
}
I wouldn't constrain the precision they put in, just make sure that it is a valid number using javascript. You might also constrain input to only include numbers and a period.
If the user puts in something wrong (i.e. not compatible with a double type), MVC will complain when it tries to bind to the model.
its very simple
follow this method
so you have to insert DataFormatString="{0:#,##0.000#Kg}" only on gridview

Resources