ASP.Net MVC Error Validation
I have an error validation issue with an int.
I have validation for a customer name:
if (String.IsNullOrEmpty开发者_运维知识库(CustomerName))
yield return new RuleViolation("Customer Name Required", "CustomerName");
now if I want to add validation for a city, in this case I have a CityID that gets saved as type int, so I can't write my if statement the same way...because there's no int.IsNullOrEmpty method. Let's say the user didn't select the dropdown for city - it's basically saving with no value.
What's the best way to write my validation statement for an int?
UPDATE:Here's a sample of what I have for my form in my view:
<% using (Html.BeginForm())
{%>
<fieldset>
<legend>Add a new customer</legend>
<p>
<label for="CustomerName">Customer Name:</label>
<%= Html.TextBox("CustomerName")%>
<%= Html.ValidationMessage("CustomerName", "*")%>
<label for="CityID">City:</label>
<%= Html.DropDownList("CityID", Model.Cities as SelectList, "Select City")%>
<%= Html.ValidationMessage("CityID", "*")%>
<input type="submit" value="Create New Customer" />
</p>
</fieldset>
<% } %>
and my view model looks like this:
public class CustomerFormViewModel
{
//Properties
public Customer Customer { get; set; }
public SelectList Cities { get; set; }
//Constructor
public CustomerFormViewModel(Customer customer)
{
CustomerRepository customerRepository = new CustomerRepository();
Customer = customer;
Cities = new SelectList(customerRepository.FindAllCities(), "CityID", "CityName");
}
}
use nullable ints,
int? i = null;
I had this same exact requirement a week ago. You can solve this in two ways.
1) In Dropdown you will always have "Please Select" with default value as -1. When a form is submitted and no city is selected then MVC model will bind -1 (default value) for CityID. So you can always check if CityID > 0 else "raise error"
2) Use c# 3.0 feature Nullable Int (int?) for CityID which means your CityID can also be null. If no value is passed for CityID, your cityID will always be null.
You can set a default value in the route config. If you set the default to a value you know is invalid then you can just check for that value. If your cities are numbered 1 through X then set the default at -1 and check for that.
If you get the input in a string format, then try to use regular expression to validate the integer format.
Regex rxNums = new Regex(@"^\d+$"); // Any positive decimal
if (!rxNums.IsMatch(cityId))
{
yield return new RuleViolation("city id Required", "cityId");
}
If you get the value in the integer format, then you just check if the value is larger than 0 or not.
精彩评论