ASP MVC Validation - asp.net-mvc

I need to perform validation on a textbox and Dropdown which triggers only when both the values are empty and does nothing when one of the value is empty. How would i implement it? Do i need to create a custom validator? Below is my Model and View
Model
public class CustomValidators
{
[Required]
[Required(ErrorMessage = "State Required")]
public string drpStateId { set; get; }
public System.Web.Mvc.SelectList drpState { set; get; }
[Required(ErrorMessage ="Region Required")]
public string txtRegion { set; get; }
}
View
#model InterviewTest.Models.CustomValidators
#{
ViewBag.Title = "Custom Validator";
Layout = "~/Views/_Layout.cshtml";
}
<p>#Html.ActionLink("< Back", "Index")</p>
#using (Html.BeginForm("CustomValidatorPost"))
{
#Html.ValidationSummary()
<div class="container-fluid">
<div class="row">
<div class="col-sm-3">
<div class="form-group">
#Html.DropDownListFor(c => c.drpStateId, Model.drpState, "", new { #class = "form-control" })
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.TextBoxFor(x => Model.txtRegion, new { #class = "form-control" })
#*<input type="text" id="txtRegion" name="txtRegion" class="form-control" />*#
</div>
</div>
<div class="col-sm-3">
<button type="submit" name="btnSubmit" id="btnSubmit" class="btn btn-default">Submit</button>
</div>
</div>
</div>
}

There is no out of the box validation that works on 2 fields except for the compare validator, so in your case you have to create a custom validation.
You can create a JavaScript function and fire it on onchange on both the two text boxes and within it check the values and if both are empty, show an error message and prevent the form from being submitted, you can achieve that using JQuery validation by adding a custom validator, see this link for more details https://jqueryvalidation.org/jQuery.validator.addMethod/
On Server side, you can do a simple if statement in the controller action to validate that both the values are not empty and if both are empty, then add an error to the ModelState

Related

Date DataAnnotation validation attribute not working - shows the time

Not working. Date comes back from a database field. Shows as:
When it is not set from a database as there is no birth date, I get a little red dot top left. Shows as:
I don't want the time included. I have a data annotation display format but it does not seem to take affect.
My Model(not showing other fields) is:
using System;
using System.ComponentModel.DataAnnotations;
namespace GbngWebClient.Models
{
public class UserProfileForMaintViewModel
{
// Can be null.
[Required]
[Display(Name = "Birth Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM-dd-yyyy}", ApplyFormatInEditMode = true)]
[RegularExpression(#"(((0[1-9]|1[0-2])\/(0|1)[0-9]|2[0-9]|3[0-1])\/((19|20)\d\d))$", ErrorMessage = "Invalid date format.")]
public DateTime BirthDate { get; set; }
}
}
My view (not showing other fields) is:
#model GbngWebClient.Models.UserProfileForMaintViewModel
<h1 class="page-header">User Profile Maintenance</h1>
#{
ViewBag.Title = "UserProfileMaint";
Layout = "~/Views/Shared/_LayoutUser.cshtml";
}
#using (Html.BeginForm("UpdateUserProfile", "UserProfiler", FormMethod.Post))
{
<div style="margin-top:10px;"></div>
<div class="panel panel-default">
<div class="panel-heading">Your Profile</div>
<div class="panel-body">
<div class="row">
<div class="row">
<div class="col-md-3">
#Html.LabelFor(model => model.BirthDate, new { #class = "manadatory" })
#Html.TextBoxFor(model => model.BirthDate, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.BirthDate, "", new { #class = "text-danger" })
</div>
<div class="col-md-3"></div>
</div>
<div style="margin-top:10px;"></div>
<div class="row">
<div class="form-group">
<div class="col-md-offset-0 col-md-12">
#* Submit button. *#
<input type="submit" value="Save" class="btn btn-info" />
</div>
</div>
</div>
</div>
</div>
}
From my previous experience I found out that it is much easier to deal with a string than a DateTime variable. So I usually use it as a hack. You can have an extra text field in your ViewModel and format it from the controller for the view -
public ActionResult Custom2()
{
var profile = new Profile();
profile.DoB = DateTime.Now.Date;
profile.DoBText = profile.DoB.ToString("yyyy-MM-dd");
return View(profile);
}
Now the view can accept the text data without any problem
#model mvcDeploymentTest.Models.Profile
#{
ViewBag.Title = "Custom2";
}
<h2>Custom2</h2>
#using (Html.BeginForm("PostTest", "Home", FormMethod.Post))
{
#Html.TextBoxFor(model => model.DoBText, new { #class = "form-control", Type = "date" })
<input type="submit" value="Submit" />
}
And once posted, you can parse the changed text value to datetime again with any formatting you want
[HttpPost]
public void PostTest(Profile myProfile)
{
DateTime dateValue;
if (!string.IsNullOrEmpty(myProfile.DoBText))
{
DateTime.TryParseExact(myProfile.DoBText,"yyyy-MM-dd", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dateValue);
myProfile.DoB = dateValue;
}
return;
}
ApplyFormatInEditMode is only used/applied when using EditorFor - you have to use the overload for TextBoxFor which accepts a format string in order to get a formatted output in the rendered <input />.
#Html.TextBoxFor(model => model.BirthDate, "{0:d}", new { #class = "form-control" })
{0:d} will apply whatever short date format matches your app's culture settings. Replace that with a custom format string if you want something else.
If you want to use your browser's native date input (<input type="date" />), you'll need to use an ISO-8601 short date, which is YYYY-MM-DD. An example:
#Html.TextBoxFor(model => model.BirthDate, "{0:yyyy-MM-dd}", new { #class = "form-control", #type = "date" })
The default modelbinder knows how to transform that into a DateTime object, which you can then format into whatever else you wanted/needed.

How to make your button on a form using asp.net-mvc work?

I have a button, it does not seem to create new users to my database. What it does it only inherits user validaton to my Login method and need some guidance to this please and thanks. Below is the logic what i am trying to do. What i want to do my create button must be able to create new users if not exist to the database.
Controller:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Create(CreateModel objSubmit)
{
ViewBag.Msg = "Details submitted successfully";
return View(objSubmit);
}
// This is for login, and its hits this method each time.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(Login login)
{
if (ModelState.IsValid)
{
bool success = WebSecurity.Login(login.username, login.password, false);
var UserID = GetUserID_By_UserName(login.username);
var LoginType = GetRoleBy_UserID(Convert.ToString(UserID));
if (success == true)
{
if (string.IsNullOrEmpty(Convert.ToString(LoginType)))
{
ModelState.AddModelError("Error", "Rights to User are not Provide Contact to Admin");
return View(login);
}
else
{
Session["Name"] = login.username;
Session["UserID"] = UserID;
Session["LoginType"] = LoginType;
if (Roles.IsUserInRole(login.username, "Admin"))
{
return RedirectToAction("AdminDashboard", "Dashboard");
}
else
{
return RedirectToAction("UserDashboard", "Dashboard");
}
}
}
else
{
ModelState.AddModelError("Error", "Please enter valid Username and Password");
return View(login);
}
}
else
{
ModelState.AddModelError("Error", "Please enter Username and Password");
return View(login);
}
}
Model:
namespace eNtsaPortalWebsiteProject.Models
{
public class CreateModel
{
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string password { get; set; }
[Required]
public string username { get; set; }
}
}
// View for login
<div data-="mainContent">
<section class="container">
<div class="logo col-sm-12 text-center col-md-12"> <img alt="" src="~/Images/eNtsa.png" /></div>
<div class="clearfix"></div>
<div class="container">
<div class="row">
<div id="MyWizard" class="formArea LRmargin">
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div id="divMessage" class="text-center col-md-12 col-md-offset-12 alert-success">
#Html.ValidationSummary()
</div>
<div class="col-md-12 col-md-offset-10 col-xs-12">
<div class="loginPage panel-info">
<div class="form-group"><span class=""><i class="glyphicon glyphicon-user">Username:</i></span>
#Html.TextBoxFor(model => model.username, new { #class = "form-control text-center", autocomplete = "off" })
#Html.ValidationMessageFor(model => model.username)
</div>
<div class="form-group">
<span class=""><i class="glyphicon glyphicon-lock">Password:</i></span>
#Html.PasswordFor(model => model.password, new { #class = "form-control text-center", autocomplete = "off" })
#Html.ValidationMessageFor(model => model.password)
</div>
</div>
<div class="form-group">
<input id="BtnLogin" type="submit" class="btn btn-success btn-pressure" name="BtnLogin" value="Login" />
<input type ="Submit" class="btn btn-info btn-pressure" name="BtnCreate" value="Create" />
</div>
</div>
}
<div class="clear"></div>
</div>
</div>
</div>
</section>
</div>
View for creating user:
<div class="mainContent">
<section class="container">
<div class="logo col-sm-12 text-center col-md-10">
<img alt="" src="~/Images/eNtsa.png"/>
</div>
<div class="container">
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div id="divMessage" class="text-center col-md-12 col-md-offset-12 alert-success">
#Html.ValidationSummary()
</div>
<div class="col-md-12 col-md-offset-10 col-xs-12">
<div class="glyphicon-registration-mark">
<div class="form-group"><span class=""><i class="glyphicon glyphicon-user">Username:</i></span>
#Html.TextBoxFor(model=>model.username, new {#class ="form-control text-center", automplete="off" })
#Html.ValidationMessageFor(model=>model.username)
</div>
<div class="form-group">
<span class=""><i class="glyphicon glyphicon-lock">Password:</i></span>
#Html.PasswordFor(model=>model.password, new {#class = "form-control text-center", autocomplete="off" })
#Html.ValidationMessageFor(model=>model.password)
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-success btn-pressure" name="BtnSubmit" value="Submit"/>
</div>
</div>
}
</div>
</section>
</div>
The button is working - that isn't the problem that you're having.
You can have multiple buttons to submit the form but they will return to the same place, either:
a) the controller/action specified in the "action" property of the form
b) if no action is specified then the default location - in your case there isn't one directly specified so it is posting back to the default location.
(see: How to link HTML5 form action to Controller ActionResult method in ASP.NET MVC 4)
The easiest way to accomplish what you're trying to do would be refactor your controller and branch the logic depending on what the value is of the submit button.
(see: MVC razor form with multiple different submit buttons?
and How to handle two submit buttons on MVC view)
This will require some refactoring of the code that you have written, but it is the most straightforward way of achieving what you're trying to do.
In very basic terms it would look something like this:
Model:
namespace eNtsaPortalWebsiteProject.Models
{
public class LoginCreateModel
{
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string password { get; set; }
[Required]
public string username { get; set; }
public string btnSubmit { get; set; } // both buttons will have the same name on your form, with different values ("Create" or "Login")
}
}
Controller:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginCreateModel objSubmit)
{
if (objSubmit.btnSubmit == "Create")
{
// Handle creation logic here
}
if (objSubmit.btnSubmit == "Login")
{
// Handle login logic here
}
return View(objSubmit);
}

How to validate the HTML controls with data annotations in MVC?

In .Net MVC. I have a html control. Inorder to bind it with the model property I am using name attribute. How do we get the validations(using data annotation) provided in the model class property into the html control?
In Cshtml
#using (Html.BeginForm("ClaimWarranty", "WarrentyClaim", FormMethod.Post, new{ enctype = "multipart/form-data" }))
{
<div class="form-group row">
<label for="" class="col-md-2 col-form-label input-label">Email Address:</label>
<div class="col-md-8">
<input type="text" name="Emailaddress" class="form-control input-style" placeholder="example#company.com">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" onclick="ValidateFileSize()" class="btn btn-default" />
</div>
</div>
}
//The model class is below;
public class ClaimWarranty
{
[Required(ErrorMessage = "Email ID is Required")]
[DataType(DataType.EmailAddress)]
[MaxLength(50)]
[RegularExpression(#"[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Incorrect Email Format")]
public string Emailaddress { get; set; }
}
I am using the name property to bind the text box to the model property .
<input type="text" name="Emailaddress" class="form-control input-style" placeholder="example#company.com">
How do I get the validations in the html control ,provided in the model class (using the data annotations) as shown above without using jquery validations or razor code?
In View
#model Demo.Models.Student
#using (Html.BeginForm("SaveStudent", "Student", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
#Html.LabelFor(model =>model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model =>model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model =>model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btnbtn-primary" />
</div>
</div>
}
In Model
public class Student
{
[Required(ErrorMessage = "Please enter name"), MaxLength(30)]
public string Name { get; set; }
}
By default, ASP.Net MVC framework executes validation logic during model binding. In Controller side, we need to check
if (ModelState.IsValid)
{
}
OR We can also check Individual validation, as shown below:
if (ModelState.IsValidField("LastName") == false)
if(!ModelState.IsValid)
{
// you can get the error information from model state, convert it into list
var validationErrors = ModelState.Values.Where(E => E.Errors.Count > 0)
.SelectMany(E => E.Errors)
.Select(E => E.ErrorMessage)
.ToList();
// now you have got the list of errors, you will need to pass it to view
// you can use view model, viewbag etc
ViewBag.ErrorList = validationErrors;
return View();
}
else
{
// perform your business operation, save the data to database
return View();
}
On View Page -
you have to add check for validation error list
if(ViewBag.ErrorList != null)
{
foreach(var errorMessage in ViewBag.ErrorList)
{
// here you can display the error message and format in html
}
}
Way you can display error on view page
1. #Html.ValidationSummary() - It will display summary of the validation errors
2. #Html.ValidationMessageFor(x => x.Emailaddress) - It will display error message
for specific property
3. you have to manually retrieve the error information from model state and then store it in list and pass to the view page.

Two Ajax forms, one view model. Validation only works for one

I've got two forms on my page. My viewmodel looks like this:
public class HomeViewModel
{
[Required(ErrorMessage = "We kind of need an email address!")]
[EmailAddress(ErrorMessage = "This isn't an email address!")]
public string Email { get; set; }
public ContactForm ContactForm { get; set; }
}
ContactForm:
public class ContactForm
{
[Required(ErrorMessage = "We need your name, please!")]
public string Name { get; set; }
[Required(ErrorMessage = "We need your email, please!")]
[EmailAddress(ErrorMessage = "This isn't an email address!")]
public string EmailAddress { get; set; }
[Required(ErrorMessage = "Please elaborate a little!")]
public string Message { get; set; }
}
First form action:
public ActionResult FreeConsultSubmit(HomeViewModel model)
{
if (ModelState.IsValid)
{
//do stuff
}
return PartialView("_SubmitResult", false);
}
Second Action:
public ActionResult ContactSubmit(HomeViewModel model)
{
if (ModelState.IsValid)
{
//dostuff
}
return PartialView("_SubmitContactResult", false);
}
First Ajax Form
#using (Ajax.BeginForm("FreeConsultSubmit", new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "FreeConsultResults"
}))
{
<div id="FreeConsultResults">
<div class="row">
<div class="small-4 columns small-centered text-center splashEmail">
#Html.TextBoxFor(m => m.Email, new { #placeholder = "Please enter your email..." })
#Html.ValidationMessageFor(m => m.Email)
</div>
</div>
<div class="row">
<div class="small-5 columns small-centered text-center">
<input type="submit" class="hvr-border-fade splashCallToAction" value="Get Started" />
</div>
</div>
</div>
}
Second Ajax Form:
#using (Ajax.BeginForm("ContactSubmit", new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "ContactSubmitResults"
}))
{
<div id="ContactSubmitResults">
<div class="row">
<div class="small-12 columns small-centered">
#Html.TextBoxFor(m => m.ContactForm.Name, new { #placeholder = "Your Name" })
#Html.ValidationMessageFor(m => m.ContactForm.Name)
#Html.TextBoxFor(m => m.ContactForm.EmailAddress, new { #placeholder = "Your Email Address" })
#Html.ValidationMessageFor(m => m.ContactForm.EmailAddress)
#Html.TextAreaFor(m => m.ContactForm.Message, new { #placeholder = "Your Message", #class = "contactMessage" })
#Html.ValidationMessageFor(m => m.ContactForm.Message)
</div>
</div>
<div class="row">
<div class="small-12 columns small-centered text-center">
<a href="">
<input type="submit" class="hvr-border-fade sendMessageSmall" value="Send Message" />
</a>
</div>
</div>
</div>
}
I've got everything wired up fine, and client side validation works as it should. This may be overkill, but I also wanted to set up server side validation.
The issue is, when submitting the first form (just the email string), I check if the ModelState is valid, and it is. If you drill down into the ModelState, you see that only 1 property is being looked at.
If you submit the second form though (the ContactForm), the ModelState.IsValid returns false, and if you drill down, you see that it's looking at 4 properties (the 3 ContactForm properties, plus the string email). Since the email string is required, it fails.
I'm confused as to why it works for one, but not the other. I could just remove the server side validation, but I'd at least like to know why this is the case. I could also remove the error from the ModelState, but that doesn't seem elegant at all.
If you simply are trying to have two separate forms within one view, you're probably better off splitting the forms into separate "sub views" and child actions, and then using #Html.Action() to render them in place.
Here's an example:
Models
I'd remove the ContactForm model from HomeViewModel, and rename HomeViewModel to ConsultingForm (to match your naming convention for the contact model):
public class ConsultingForm
{
[Required(ErrorMessage = "We kind of need an email address!")]
[EmailAddress(ErrorMessage = "This isn't an email address!")]
public string Email { get; set; }
}
public class ContactForm
{
[Required(ErrorMessage = "We need your name, please!")]
public string Name { get; set; }
[Required(ErrorMessage = "We need your email, please!")]
[EmailAddress(ErrorMessage = "This isn't an email address!")]
public string EmailAddress { get; set; }
[Required(ErrorMessage = "Please elaborate a little!")]
public string Message { get; set; }
}
Controller
Add "child" actions, like those below:
public class HomeController : Controller
{
public ActionResult Home()
{
return View();
}
[ChildActionOnly, HttpGet]
public ActionResult ConsultingRequest()
{
var model = new ConsultingForm();
return View(model);
}
[ChildActionOnly, HttpGet]
public ActionResult ContactRequest()
{
var model = new ContactForm();
return View(model);
}
}
The ChildActionOnlyAttribute marks the action as a child action. From the MSDN:
A child action method renders inline HTML markup for part of a view
instead of rendering a whole view.
Views
Your first subview will be the same as you already have:
#using (Ajax.BeginForm("FreeConsultSubmit", new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "FreeConsultResults"
}))
{
<div id="FreeConsultResults">
<div class="row">
<div class="small-4 columns small-centered text-center splashEmail">
#Html.TextBoxFor(m => m.Email, new { #placeholder = "Please enter your email..." })
#Html.ValidationMessageFor(m => m.Email)
</div>
</div>
<div class="row">
<div class="small-5 columns small-centered text-center">
<input type="submit" class="hvr-border-fade splashCallToAction" value="Get Started" />
</div>
</div>
</div>
}
Your second subview simply needs to remove the extra "step" in the property bindings:
#using (Ajax.BeginForm("ContactSubmit", new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "ContactSubmitResults"
}))
{
<div id="ContactSubmitResults">
<div class="row">
<div class="small-12 columns small-centered">
#Html.TextBoxFor(m => m.Name, new { #placeholder = "Your Name" })
#Html.ValidationMessageFor(m => m.Name)
#Html.TextBoxFor(m => m.EmailAddress, new { #placeholder = "Your Email Address" })
#Html.ValidationMessageFor(m => m.EmailAddress)
#Html.TextAreaFor(m => m.Message, new { #placeholder = "Your Message", #class = "contactMessage" })
#Html.ValidationMessageFor(m => m.Message)
</div>
</div>
<div class="row">
<div class="small-12 columns small-centered text-center">
<a href="">
<input type="submit" class="hvr-border-fade sendMessageSmall" value="Send Message" />
</a>
</div>
</div>
</div>
}
The "wrapper", or parent view, will look something like:
<div class="whatever">
#Html.Action("ConsultingRequest", "Home")
#Html.Action("ContactRequest", "Home")
</div>
If you inspect the rendered HTML, you'll see that each form is properly bound to only its model's properties, so when you post each form, only those properties are model-bound and validated.

IValidatableObject.Validate does not fire if DataAnnoations add ValidationResult

With a standard ASP.NET MVC controller and view and a model that both implements IValidatableObject and has DataAnnotations, the Validate method never fires if the DataAnnotations generate an exception.
Here's the model...
public class ModelStaticDA : IValidatableObject {
public long Id { get; set; }
[EmailAddress]
public string EmailAddress { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
yield return new ValidationResult("MODEL NOT VALID!")
}
}
Here's the view (client validation is disabled for this demo)...
#model BindingAndValidation.Models.ModelStaticDA
#{
ViewBag.Title = "Create";
HtmlHelper.ClientValidationEnabled = false;
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>ModelStaticDA</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.EmailAddress, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.EmailAddress)
#Html.ValidationMessageFor(model => model.EmailAddress)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
If you post something like "invalid" to EmailAddress, only the DataAnnotation message displays. If you post a valid e-mail address, the message from Validate displays.
Is this the correct behavior? If so, why? If not, what am I doing wrong?
You are doing everything right, that's the behavior. My guess it was designed this way to avoid having to validate again while working with the properties inside the Validate method, you know that when it's called you are working with valid data, and you can do things that require valid data.

Resources