Using the Confirm Attribute in MVC 3 Effectively


This article mainly focuses on how to make sure that the properties within the particular class are matched and operations are performed well.  If it does not matches then it should fire off a validation to user stating that the data entered according to these properties does not match. So lets drill out and take a look how to implement it.


Let's take Student.cs with an extra property called ConfirmEmail. So This Property should match with the exsisting email property else should pop out an error to the user stating that the email entered is incorrect.

So the newly created property looks like this:

public string ConfirmEmail { getset; }

So let's add some attributes to this class where it should validate with exsisting Email Property

Besides that, we are also setting the datatype should be as an email type:

[DataType(DataType.EmailAddress)]

So, the complete code of student.cs looks like this

Student.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace MVC_Basic_Application.Models
{
    public class Student
    {
        [Key]

        public int StudentId { getset; }

        [Required(ErrorMessage = "Please Enter FirstName")]
        [StringLength(10, ErrorMessage = "FirstName morethan 10 charcs")]
        public string FirstName { getset; }

        [Required(ErrorMessage = "Please Enter LastName")]
        [StringLength(10, ErrorMessage = "LastName morethan 10 charcs")]
        public string LastName { getset; }

        [Range(5, 50, ErrorMessage = "Age Should Be Between 5 and 50")]
        public int Age { getset; }
        [Required(ErrorMessage = "Please Enter Location")]
        [StringLength(10, ErrorMessage = "Location morethan 10 charcs")]
        public string Location { getset; }

        [Required(ErrorMessage = "Email is required")]
        [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                           @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                           @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
                           ErrorMessage = "Email appears to be invalid.")]
        [DataType(DataType.EmailAddress)]
        public string Email { getset; }

        [Required(ErrorMessage = "Confirm Email is required")]
        [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                           @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                           @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
                           ErrorMessage = "Email appears to be invalid.")]
        [DataType(DataType.EmailAddress)]
        [Compare("Email",ErrorMessage="Email Should Match")]
        public string ConfirmEmail { getset; }
    }
}



Let's also modify the StudentStateIntializer.cs . So Complete Code of StudentStateIntializer.cs looks like this:

StudentStateIntializer.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace MVC_Basic_Application.Models
{
    public class StudentStateIntializer:DropCreateDatabaseIfModelChanges<StudentStateEntities>
    {
        protected override void Seed(StudentStateEntities context)
        {
            var stu = new List<Student>
            {
                new Student
                {
                    StudentId=1,
                    FirstName="Vijay",
                    LastName="Prativadi",
                    Location="Banglore",
                    Age=25,
                    Email="[email protected]",
                    ConfirmEmail=
"[email protected]"

                },
                 new Student
                {
                    StudentId=2,
                    FirstName="Uday",
                    LastName="Prativadi",
                    Location="Mumbai",
                    Age=28,
                    Email="[email protected]",
                    ConfirmEmail="[email protected]"
                }
            };
            stu.ForEach(d=>context.Students.Add(d));
        }
    }
}



We are almost done with major task now , So let's rebuild and run the application . So, the output of Index.cshtml looks like this:

one.jpg

The validations for the fields are shown if we do not enter data, where the screen looks like this:

Two.png

If we enter incorrect unmatched email the validation screen for this looks like this:


Three.png

If we enter incorrect email format the validation screen for this looks like this:

fourth.png
When are all good, no validations then screen looks like this:

Five.png
Finally, data added to database successfully which looks like this from our view screen :

Sixth.png

I hope this article is useful to you.

Thanks for reading this article....I look Forward for Comments and Feedback

 


Similar Articles
MVC Corporation
MVC Corporation is consulting and IT services based company.