How to validate textboxes in ASP.NET MVC - c#

I am new to ASP.NET MVC and am trying to validate a text-box. Basically, if user inputs less than 2 or a non number how can I get the error to display. Here's the tutorial I am trying to follow.
I have my code below.
Create View:
<%= Html.ValidationSummary()%>
<%= using (HtmlBeginForm()){%>
<div class="half-col">
<label for="Amount">Amount:</label>
<%= Html.TextBox("Amount")%>
<%= Html.ValidationMessage("Amount", "*")%>
</div>
Create Controller:
[AcceptVerbs (HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude ="ID")] Charity productToCreate)
{
//Validation
if (productToCreate.Amount < 2)
ModelState.AddModelError("Amount, Greater than 2 please");
return View(db.Donations.OrderByDescending(x => x.ID).Take(5).ToList()); //Display 5 recent records from table
}
Model:
public class Charity
{
public int ID { get; set; }
public string DisplayName { get; set; }
public DateTime Date { get; set; }
public Double Amount { get; set; }
public Double TaxBonus { get; set; }
public String Comment { get; set; }
}
Error:
CS1501 No overload for method 'AddModelError' takes 1 CharitySite

You are adding the error to your modelstate incorrectly. You can read more about the ModelStateDictionary on the MSDN
AddModelError takes 2 parameters, so you would want:
ModelState.AddModelError("Amount", "Greater Than 2 Please.");
Having said that, you can use attributes to validate your model properties so you don't have to write all of that code by hand. Below is an example using the Range attribute. The RegularExpression attribute could also work. Here is an MSDN article containing information about the different types of attributes.
public class Charity
{
public int ID { get; set; }
public string DisplayName { get; set; }
public DateTime Date { get; set; }
[Range(2, Int32.MaxValue, ErrorMessage = "The value must be greater than 2")]
public Double Amount { get; set; }
public Double TaxBonus { get; set; }
public String Comment { get; set; }
}
Also as a side note, the tutorial you are following is for MVC 1&2. Unless you HAVE to use / learn that. I would recommend following the tutorial for MVC 5 here.

Change this line:
ModelState.AddModelError("Amount, Greater than 2 please");
to:
ModelState.AddModelError("Amount ", "Amount, Greater than 2 please");
The first parameter is the member of the model being validated; it can be an empty string just to indicate an error not associated to a field. By specifying the Amount field, internally it uses that to highlight the erroring field (the control should have input-validation-error CSS class added to it) if you are using all of the client-side validation pieces.

ModelState.AddModelError takes 2 arguments, not 1. Link to MSDN ModelStateDictionary.AddModelError Method.
ModelState.AddModelError("Amount", "Greater than 2 please");

if (productToCreate.Amount < 2)
ModelState.AddModelError("Amount", "Greater than 2 please");

Related

Cost must be multiple by 5

I am working small application with basic CRUD operation and I have Product Model.
In this model I have something like
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public int amountAvailable { get; set; }
public double cost { get; set; }
[ForeignKey(nameof(User))]
public int UserId { get; set; }
public User Users { get; set; }
}
Right now, I need some shortcut or some hack how to make cost (cost of the product), but it should be a multiple of 5, meaning the price can be 5,10,15,20,25,30... etc.
Is there anything which I can force user to put price something like thiss?
I try with [DataAnnotation] and using Range but I think this will not work.
Try:
public class MultipleOf5Attribute : ValidationAttribute
{
public override bool IsValid(object value)
{
return ((int)value) % 5 == 0;
}
}
use the decimal instead of the int
You can make cost variable as a prop and round there any given value by user till it is valid.
You can use a JS at the end of your view which is probably better as you will have a front end validation rather than posting the form before checking if it’s wrong (sorry I’m using my phone to type the suggested answer so may not be formatted properly) but something like this:
<script>
document.getElementById("Submit_btn_id").addEventListener('click',function ()
{
//get the value entered in the input field
var userEnterANumber = document.getElementById('input_id').value
if (userEnterANumber % 5 == 0)
{
console.write('This is a multiple of 5')
//turn off the required attribute from the input field
document.getElementById("input_id").required = false;
}
else
{
console.write('Not a multiple of 5')
//set the required attribute on the input field
document.getElementById("input_id").required = true;
}
});
</script>

MVC Routing with Period in parameter name

I am trying to implement a remote validation using entity framework in an MVC application. I need help trying to define the action signature and the appropriate route config. I have the following class in my model:
public class FiscalReports
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long id { get; set; }
public Int64 Counter { get; set; }
public short FiscalYear { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MMM dd, yyyy}")]
[DisplayFormat(DataFormatString = "${0:N0}")]
[Remote("ValidateSalary", "FiscalReports", AdditionalFields ="Counter, FiscalYear")]
public int? Salaries { get; set; }
}
I have a viewmodel which is used for a view that contains several of the above objects.
public class FiscalReportVM
{
public FiscalReports CurrentFR { get; set; }
public FiscalReports ReportedToDate { get; set; }
public FiscalReports BudgetToDate { get; set; }
}
The Validation action is in the FiscalReports controller is as follows:
public JsonResult ValidateSalary(int Salaries, short FiscalYear, int Counter)
{
return ValidateFiscalField(Salaries, FiscalYear, Counter, "Salaries");
}
In the view I am using the HTML helper
#Html.EditorFor(model=>model.CurrentFR.Salaries)
This generates the field and validation correctly. Generated HTML is below
input data-val="true" data-val-number="The field Salaries must be a number." data-val-remote="'Salaries'; is invalid." data-val-remote-additionalfields="*.Salaries,*.Counter,*.FiscalYear" data-val-remote-url="/FiscalReports/ValidateSalary" name="CurrentFR.Salaries" type="number" value="" />
The validation request is firing properly and in fiddler I see the following request:
http://localhost:50409/FiscalReports/ValidateSalary?CurrentFR.Salaries=27000&CurrentFR.Counter=4773&CurrentFR.FiscalYear=2
My problem is that I have trouble defining a route and action with the variables in dotted notation. The action definition does not accept dotted parameters (Can't do ValidateSalary(int CurrentFR.Salaries,....). I need help trying to define the action signature and the appropriate route config.
Can't you just use a bit of JQuery to change the name attribute? Something to the effect of:
$("CurrentFR.Salaries").attr('name', 'Salaries')
Remember having a not dissimilar issue and I just temporarily changed the name in the view, and then changed in back in the action.

MVC5 - How to validate compound checks?

I am working on a MVC Razor project that needs some more complex input validations. We are using ViewModels to remove all access to the data model from the controller without going through a logic layer. What we need to solve is how to do the following types of validations:
User selected date is after another date value:
// Read Only for user
public DateTime StartDate { get; set; }
// Must be after StartDate
public DateTime OccurredAt { get; set; }
Sum of user inputs for N (variable) fields do not exceed the value of another field.
// Read only for user
public double StartingAmount { get; set; }
// Sum of these fields must be less than starting amount
public double AmountTransfered { get; set; }
public double AmountLosses { get; set; }
public double AmountSampled { get; set; }
// Validation Check
if (StartingAmount - (AmountTransfered + AmountLosses + AmountSampled) > 0)
isValid = true;
I am new to MVC, and most validation things I find on Google are from 2010 and are loaded with JavaScript to do custom implementations.
I am hoping that there are newer mechanisms to perform compound validation using attributes to define what fields are related. I suspect that the solution for both of these will be very similar, just a different set of parameters and data types.

ASP.NET MVC data annotations attribute Range set from another property value

Hi I have following in my Asp.net MVc Model
TestModel.cs
public class TestModel
{
public double OpeningAmount { get; set; }
[Required(ErrorMessage="Required")]
[Display(Name = "amount")]
[Range(0 , double.MaxValue, ErrorMessage = "The value must be greater than 0")]
public string amount { get; set; }
}
Now from my controller "OpeningAmount " is assign .
Finaly when I submit form I want to check that "amount" must be greater than "OpeningAmonut" . so want to set Range dynamically like
[Range(minimum = OpeningAmount , double.MaxValue, ErrorMessage = "The value must be greater than 0")]
I do not want to use only Jquery or javascript because it will check only client side so possible I can set Range attribute minimum dynamically than it would be great for.
Recently there's been an amazing nuget that does just that: dynamic annotations and it's called ExpressiveAnnotations
It allows you to do things that weren't possible before such as
[AssertThat("ReturnDate >= Today()")]
public DateTime? ReturnDate { get; set; }
or even
public bool GoAbroad { get; set; }
[RequiredIf("GoAbroad == true")]
public string PassportNumber { get; set; }
There's no built-in attribute which can work with dependence between properties.
So if you want to work with attributes, you'll have to write a custom one.
Se here for an example of what you need.
You can also take a look at dataannotationsextensions.org
Another solution would be to work with a validation library, like (the very nice) FluentValidation .

Validating Against Property of 2nd Model

As part of my objective of learning a new skill at work I am attempting to develop an employee management system in ASP.NET MVC (MVC 4).
I am trying to follow the convention of performing all validation at the model level (not only because this is what I have read is recommended but also as there is talk of a desktop app that may use parts of the model so I want to ensure any constraints are enforced in that app too!).
My issue is, I have some data on the Person class (RemainingHoliday). When create a HolidayRequest I want to ensure that the request is not for a greater number of days than the person has remaining.
How would I go about doing this? I know that I can create my own validation rules by extending the ValidationAttribute, but how would I get from the HolidayRequest class to the Person class within here?
A snippet of the models:
public class Person
{
public string PersonID { get; set; } // this is populated with Users AD Guid
public string HolidayEntitlement { get; set; }
public virtual ICollection<HolidayRequest> Holidays { get; set; }
public int TotalEntitlement(int year = -1)
{
return this.HolidayEntitlement + this.HolidayAdjustments.Where(a => a.LeaveYear.Year == year).Sum(a => a.Adjustment);
}
public int RemainingHoliday(int year = -1)
{
return this.TotalEntitlement(year) - this.Holidays.Where(h => h.Start.Year == year).Where(h => h.Status != HolidayStatus.Rejected).Sum(h => h.Duration);
}
}
public class HolidayRequest
{
public string HolidayId { get; set; }
public DateTime Start { get; set; }
public DateTime Finish { get; set; }
public int Duration { get; set; } // This cannot be greater than Person.RemainingHoliday
}
I would really appreciate any pointers or samples for this, or perhaps I am trying to be too ideal and this cannot be done in the model?
It seems that you are missing a reference to the person requesting the holiday in the HolidayRequest object. I would have expected to see a Person or PersonId in the HolidayRequest object. Once there, you could compute the difference between Duration and RemainingHoliday.

Categories