Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# ASP.NET MVC Forms Adding Form Validation Improving Validation CSS Styles

After added jQuery.Validate.Bootstrap.js validation, "Duration" field's still allowing value of "0" in client-validation

After we added jQuery.Validate.Bootstrap.js validation, the "Duration" field's still allowing value of "0" in client-validation, why? How can we make sure that said field behaves the same way than the "Activity" field using our custom validation in the client-side?

3 Answers

James Churchill
STAFF
James Churchill
Treehouse Teacher

Rolando,

As you noticed, our validation that checks if the "Duration" field value is greater than "0" is only implemented on the server-side. That being said, it is possible to create a custom validation attribute that will work both on the server and client, though doing so will require that you write some JavaScript code.

This article on the official ASP.NET MVC website contains a section on how to create a custom validation attribute, including how to implement the IClientModelValidator interface on your custom validation attribute class.

https://docs.asp.net/en/latest/mvc/models/validation.html#client-side-validation

Thanks ~James

Thank you, James. That article helped. Great work on the course!

Victor Johnson
Victor Johnson
24,294 Points

You could also use the 'Range' annotation to show an error similar to what you are seeing on the Activity field.

What I used was as follows: [Range(1, int.MaxValue, ErrorMessage ="The Duration field must be greater than 0")]

This means, the minimum value you can have in the field is 1, the maximum value you can have in the maximum value of a integer, and the error message is straight-forward. If you place this above the Duration property, you will see the error on the client-side if the value does not meet this criteria.

James Churchill
James Churchill
Treehouse Teacher

Victor,

That's a great idea! Though you probably should switch to using doubles to specify your range values since that's the data type that's used in the underlying model property.

[Range(1.0, double.MaxValue, ErrorMessage ="The Duration field must be greater than 0")]

Something to note about this solution, is that it wouldn't allow for values that fall between "0" and "1", though that's a minor issue, since it's not likely that an exercise activity's duration would be less than a minute.

Thanks ~James