Please enable Javascript to correctly display the contents on Dot Net Tricks!

ASP.NET MVC Registration form with Validation

  Author : Shailendra Chauhan
Updated On : 23 Nov 2016
Total Views : 175,333   
Support : MVC5, MVC4 & MVC3
 

Since registration form is a common form, so I prefer it to demonstrate the basic validation in ASP.NET MVC. I have already explained the validation with data annotation and how to enable client side validation in mvc razor, now my focus is to develop registration form with client side and server side validations.

How to do it...

Step1 : Designing Model

First of all we will design the RegistrationModel with data annotation which help us to validate the input data. Since we have no attribute to validate drop down list and checkbox, so I have created custom attributes "MustBeSelected" and "MustBeTrue for validating dropdownlist and checkbox respectively as shown below.

 public class RegistrationModel
 {
 [Required(ErrorMessage = "Please Enter Email Address")]
 [Display(Name = "UserName")]
 [RegularExpression(".+@.+\\..+", ErrorMessage = "Please Enter Correct Email Address")]
 public string UserName { get; set; }
 
 [Required(ErrorMessage = "Please Enter Password")]
 [StringLength(50, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
 [DataType(DataType.Password)]
 [Display(Name = "Password")]
 public string Password { get; set; }
 
 [Required(ErrorMessage = "Please Enter Confirm Password")]
 [StringLength(50, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
 [DataType(DataType.Password)]
 [Display(Name = "Confirm password")]
 [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
 public string ConfirmPassword { get; set; }
 
 [Display(Name = "Country")]
 public Country Country { get; set; }
 
 [Display(Name = "City")]
 public City City { get; set; }
 
 [Required(ErrorMessage = "Please Enter Address")]
 [Display(Name = "Address")]
 [StringLength(200)]
 public string Address { get; set; }
 
 [Required(ErrorMessage = "Please Enter Mobile No")]
 [Display(Name = "Mobile")]
 [StringLength(10, ErrorMessage = "The Mobile must contains 10 characters", MinimumLength = 10)]
 public string MobileNo { get; set; }
 
 [MustBeTrue(ErrorMessage = "Please Accept the Terms & Conditions")]
 public bool TermsAccepted { get; set; }
}

public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable // IClientValidatable for client side Validation
{
 public override bool IsValid(object value)
 {
 return value is bool && (bool)value;
 }
 // Implement IClientValidatable for client side Validation
 public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
 {
 return new ModelClientValidationRule[] { new ModelClientValidationRule { ValidationType = "checkbox", ErrorMessage = this.ErrorMessage } };
 }
}

public class MustBeSelected : ValidationAttribute, IClientValidatable // IClientValidatable for client side Validation
{
 public override bool IsValid(object value)
 {
 if (value == null || (int)value == 0)
 return false;
 else
 return true;
 }
 // Implement IClientValidatable for client side Validation
 public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
 {
 return new ModelClientValidationRule[] { new ModelClientValidationRule { ValidationType = "dropdown", ErrorMessage = this.ErrorMessage } };
 }
}

public class Country
{
 [MustBeSelected(ErrorMessage = "Please Select Country")]
 public int? ID { get; set; }
 public string Name { get; set; }
}

public class City
{
 [MustBeSelected(ErrorMessage = "Please Select City")]
 public int? ID { get; set; }
 public string Name { get; set; }
 public int? Country { get; set; }
}

}

As shown above, for creating custom attribute you need to inherit ValidationAttribute class and IClientValidatable interface for Server Side and Client Side Validation.

Step2 : Designing View

Now design the strongly-typed view on the basis of Registration Model. We will also register the client side validation that we have defined in model for the dropdownlist and checkbox by using jquery as shown below.

@model Mvc4_RegistrationForm.Models.RegistrationModel
<script type="text/jscript">
jQuery.validator.unobtrusive.adapters.add("dropdown", function (options) {
 if (options.element.tagName.toUpperCase() == "SELECT" && options.element.type.toUpperCase() == "SELECT-ONE") {
 options.rules["required"] = true;
 if (options.message) {
 options.messages["required"] = options.message;
 }
 }
});

jQuery.validator.unobtrusive.adapters.add("checkbox", function (options) {
 if (options.element.tagName.toUpperCase() == "INPUT" && options.element.type.toUpperCase() == "CHECKBOX") {
 options.rules["required"] = true;
 if (options.message) {
 options.messages["required"] = options.message;
 }
 }
});

$(function () {
 $('#Country_ID').change(function () {
 var id = $("#Country_ID :selected").val();
 if (id != "") {
 $.ajax({
 type: "GET",
 contentType: "application/json; charset=utf-8",
 url: '@Url.Action("CityList", "Home")',
 data: { "mCountry": id },
 dataType: "json"
 success: function (data) {
 var items = "";
 $.each(data, function (i, city) {
 items += "<option value='" + city.Value + "'>" + city.Text + "</option>";
 });
 $('#City_ID').html(items);
 },
 error: function (result) {
 alert('Service call failed: ' + result.status + ' Type :' + result.statusText);
 }
 });
 }
 else {
 var items = '<option value="">Select</option>';
 $('#City_ID').html(items);
 }
 });

});

</script>
 
@using (Html.BeginForm())
{
lt;fieldset>
 <legend></legend>
 <ol>
 <li>
 @Html.LabelFor(m => m.UserName)
 @Html.TextBoxFor(m => m.UserName, new { maxlength = 50 })
 @Html.ValidationMessageFor(m => m.UserName)
 </li>
 <li>
 @Html.LabelFor(m => m.Password)
 @Html.PasswordFor(m => m.Password, new { maxlength = 50, value = ViewBag.Selpwd })
 @Html.ValidationMessageFor(m => m.Password)
 </li>
 <li>
 @Html.LabelFor(m => m.ConfirmPassword)
 @Html.PasswordFor(m => m.ConfirmPassword, new { maxlength = 50, value = ViewBag.Selconfirmpwd })
 @Html.ValidationMessageFor(m => m.ConfirmPassword)
 </li>
 <li>
 @Html.LabelFor(m => m.Country)
 @Html.DropDownListFor(m => m.Country.ID, new SelectList(ViewBag.Country, "ID", "Name", ViewBag.SelCountry), new { style = "width:310px" })
 @Html.ValidationMessageFor(m => m.Country.ID)
 </li>
 lt;li>
 @Html.LabelFor(m => m.City)
 @Html.DropDownListFor(m => m.City.ID, new SelectList(ViewBag.City, "ID", "Name", ViewBag.SelCity), new { style = "width:310px" })
 @Html.ValidationMessageFor(m => m.City.ID)
 </li>
 <li>
 @Html.LabelFor(m => m.Address)
 @Html.TextAreaFor(m => m.Address, new { maxlength =200 })
 @Html.ValidationMessageFor(m => m.Address)
 </li>
 <li>
 @Html.LabelFor(m => m.MobileNo)
 @Html.TextBoxFor(m => m.MobileNo ,new { maxlength = 10 })
 @Html.ValidationMessageFor(m => m.MobileNo)
 </li>
 <li>
 @Html.CheckBoxFor(m => m.TermsAccepted) I accept the terms & conditions
 @Html.ValidationMessageFor(m => m.TermsAccepted)
 </li>
 </ol>
 <input type="submit" value="Submit" />
</fieldset>
}

Step3 : Designing Controller

In the controller defined the methods for binding Country and City dropdown lists. I am not showing the methods here. Also handle the submit button event. We should also check all the validation at server side by checking IsValid property of ModelState.

public ActionResult RegistrationForm()
{
 BindCountry();
 BindCity(0);
 return View();
}

[HttpPost]
public ActionResult RegistrationForm(RegistrationModel mRegister)
{
 //This will check Server Side Validation by using data annotation
 if (ModelState.IsValid)
 {
 return View("Completed");
 }
 else
 {
 // To DO: if client validation failed
 ViewBag.Selpwd = mRegister.Password; //for setting password value
 ViewBag.Selconfirmpwd = mRegister.ConfirmPassword;
 ViewBag.SelCountry = mRegister.Country; // for setting selected country
 BindCountry();
 ViewBag.SelCity = mRegister.City;// for setting selected city
 
 if (mRegister.Country != null)
 BindCity(mRegister.Country.ID);
 else
 BindCity(null);
 
 return View();
 }
}

How it works...

Now run the code and you will find that all the validations are working well as expected.

What do you think?

I hope you will enjoy the tips while programming with MVC Razor. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

ABOUT AUTHOR

Shailendra Chauhan
Author, Architect, Corporate Trainer and Microsoft MVP

He is the author of some of most popular e-books which encompass technical Interview on Node.js Interview Questions and Answers, ASP.NET MVC Interview Questions and Answers, AngularJS Interview Questions and Answers and LINQ Interview Questions and AnswersKnow more...

YOU MIGHT LIKE
Free Interview Books
 
COMMENTS (0)
14 DEC
ASP.NET MVC with AngularJS Development (online)

MON-FRI 07:30 AM- 09:00 AM IST

Know More
5 DEC
AngularJS Development (online)

Mon - Fri     6:30 AM-7:30 AM IST

3 DEC
AngularJS Development (offline)

SAT,SUN     11:00 AM-12:30 PM IST

3 DEC
MEAN Stack Development (offline)

Sat, Sun     (09:30 AM-11:00 AM IST)

26 NOV
ASP.NET MVC with AngularJS Development (offline)

(SAT,SUN)     03:30 PM-05:00 PM IST

24 NOV
ASP.NET MVC with AngularJS Development (online)

MON-FRI     09:30 PM-11:00 PM IST

12 NOV
ASP.NET MVC with AngularJS Development (offline)

SAT,SUN     08:00 AM-09:30 AM

3 NOV
ASP.NET MVC with AngularJS Development (online)

MON-FRI     07:30 AM-09:00 AM IST

25 OCT
.NET Development (offline)

Mon-Fri     9:00 AM-11:00 AM IST

BROWSE BY CATEGORY
 
RECENT ARTICLES
SUBSCRIBE TO LATEST NEWS
 
LIKE US ON FACEBOOK
 

Professional Speaks

+