How to validate length -- text box

4/1/2014

This article is about how to set up a validation for textbox's length. So I'll use MVC's Model State to complete server side valistion and client side validation. Bacically, use string for your ViewModel is way to go, you could use the actual type, like int, double to check length, you'll think when it's go to server side you don't need to convert from string to int and double. But, looks like Microsoft default has some problem with that, it might need some extra setting of effort to let not string type to use Length validation.

1. View Model

Created three View Model, string works fine. But Int and Double failed when post to server side and before go to controller.

2. Controller

Basically, you need to method, one for page Initatite, one for page post to server side.

3. Html

So, you need to add your ViewModel's controller to HTML, html textbox, and submit button.

4. Validatate string textbox

 

5. Type string value

Add string type to your lenght to validate, it'll validate both number and string, when has error display same error message. However, string type length validation doesn't automatic validation require, if you need to validate require validation then you need add require attribute to your View Model.

6. Int and Double type Validation(Require)

Int and Double's length validation will automatic add require validation. If you don't want to display that message, need to figure out how to set it up. Or search Google.(* sorry, don't know yet.)

7. Int and Double type Validation(Check Number)

If you enter not number to Int/Double type ViewModel textbox, .NET'll automatic check it's number or not. (*sounds good to me, if i can config message easily).

8. Int and Double type Validation

So if you type string character, it'll throw error validation message by .NET by default.

9. Falied Before come to post method

Use Int and Double, it failed by .net after you enter correct data.

In conclusion, use string type for your textbox so far, since other type has some problem, it might have way to resolve, since Microsoft .NET doing something between client and action.