Introduction

In my last article I discussed about the server side Required validation with example. In this example I am continuing the last topic and will cover the Range validation and compare validation in mvc.

Range Validation

To implement the range validation we have to use the Range attribute on the property in my model. As I am continuing the last article example, so our model class is Student.

So to implement the Range validation we have to set the Range attribute in the following in manner:-

Syntax of Range Validation

		
		[Range(18,40)]
       public int stu_age { get; set; }
		
		

so I have put range validation on student age as it should not be more than 40 and not less than 18.

Range Validation with Error Message

We can also pass the ErrorMessage as named parameter as I already discussed it in my last article:-

		
		[Range(18,40,ErrorMessage="Age must be between 18 and 40")]
       public int stu_age { get; set; }

		
		

Compare validation

As we use Required and Range validation, similarly we can also use compare validation.

We have to set the compare attribute in the property which we want to be compared to any other property. We pass the property name to this compare attribute.

We will set the code in the following manner:-

Syntax of compare validation

		
		[Compare("stu_name")]
       public string course { get; set; }

	
		

I compared the course with student name

Note: - As I know that it doesn’t make any sense to compare course with name but to explain this validation I used it. You can use password and re-password for this task. As I didn’t include password column so I used this example

We can also pass the error message with this validation also.

Compare validation with ErrorMessage

		
		
		[Compare("stu_name",ErrorMessage="Student name and course doesn't match")]
       public string course { get; set; }

		
		

Now execute this code and enter wrong data so that validation fire:-

		
		Required Validation in MVC

		Figure 1
	
		

Email Address

For any query you can send mail at info@techaltum.com
Thanks