I want to create a small application for inserting Amount
Date
note
Account_Name
into table transaction
.
I don't want to create an action method for this, and want to use from CLI.
My business object looks like this:
public class ExpenseBO : Controller
{
public void MakeExpense(MakeExpensePayload payload)
{
var transactionAccess = new TransactionAccessController(connection);
transactionAccess.MakeTransaction(payload);
}
}
In access layer:
public void MakeTransaction(MakeExpensePayload p)
{
connection.Insert(new { p.Amount, p.Date, p.Note });
}
Model MakeExpensePayload:
public class MakeExpensePayload
{
public int Amount { get; set; }
public string note { get; set; }
public DateTime Date { get; set; }
}
I want to validate Amount
, Date
, note
, AccountName
- so for instance, Amount
cannot be negative, note
should not be empty (i.e., make note
field required). The Date
is not mandatory to provide
As I am not using action methods here, I cannot validate using model validation and data annotations.
So, where should I add validations in all these structures and how can I validate these?
CodePudding user response:
The rule of thumb is you should validate your data Once you receive it and before you start processing it, this will help neutralizing any possible threats
Client side validation is not enough as it can be bypassed, you should do validation also on server side
CodePudding user response:
If you want server side validations, I consider you can do it individually. For example:
You can create a private method where you can do validations and throw an Exception to client side to inform that this field is required :
private void GeneralValidations(MakeExpensePayload payload)
{
if(payload.Amount <= 0)
//Throw new HttpException
if(string.IsNullorEmpty(payload.Note))
//Throw new HttpException
}
then, call it into your method:
public void MakeExpense(MakeExpensePayload payload)
{
GeneralValidations(payload);
var transactionAccess = new TransactionAccessController(connection);
transactionAccess.MakeTransaction(payload);
}