ASP.NET MVC Registration form with Validation

ASP.NET MVC Registration form with Validation

04 Apr 2024
Intermediate
260K Views
14 min read

ASP.NET MVC Registration Form: An Overview

Since the 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 a registration form with client-side and server-side validations. In this MVC Tutorial, we will explore more about the ASP.NET MVC Registration form with Validation which will include the registration form in mvc3 razor, registration page in mvc3 mvc4 razor, validation on registration form in mvc3 mvc4. Consider our ASP.NET MVC Course for a better understanding of all MVC core concepts.

Registration form in mvc3 razor

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 the drop-down list and checkbox, so I have created custom attributes "MustBeSelected" and "MustBeTrue for validating the dropdown list 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 a custom attribute you need to inherit the 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 the Registration Model. We will also register the client-side validation that we have defined in the model for the drop-down list 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

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 on the server side by checking the 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();
 }
}
 

Validation of the registration form

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

Validation of the registration form
Validation of the registration form
Conclusion

So in this article, we have learned about ASP.NET MVC Registration form with Validation. I hope you enjoyed learning these concepts while programming with Asp.Net. Feel free to ask any questions from your side. Your valuable feedback or comments about this article are always welcome. Level up your career in MVC with our ASP.Net Core Certification.

FAQs

The ValidationMessageFor() displays an error message for the specified field. The ValidationSummary() displays a list of all the error messages for all the fields

Using Data Annotation attribute classes to model classes.

MVC (Model-View-Controller) is a pattern in software design commonly used to implement user interfaces, data, and controlling logic
Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 9th time in a row (2016-2024). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this