Validation in MVC 3 without a Model

I have a question on validation in mvc3. The built in validation looks great. However, I've had to use javascript in one case, causing it to be inconsistent w/look and feel (alert window vs nice red text). We have a form which contains a few fields for user input. When submitted, some ajax code fires a link which maps to a controller method that takes the values submitted from the form and kicks off processes which result in a client database being created. The question is: What is the best way to do validation on the fields (length, character, etc) since there is no model directly mapped to the fields on that form? My solution was to write some javascript functions but is there a cleaner way to do it?

 <td>@Html.TextBox("NewClientId")</td>
...            

    <script language="javascript">
       function ValidateFieldLength(min, max, element) {
            var len = element.value.length;
            if (len < min || len > max)
                return false;
            else {
                return true;
            }
        }
        function createNewClient() {
            if (!ValidateFieldLength(3,3,document.getElementById('NewClientId'))) {
            alert("Invalid Client ID length");
            return;
        }
        $.ajax({
            url: '/api/Clients',
            type: 'PUT',
            data: JSON.stringify({
                ClientId: $('#NewClientId').val(),
                Name: $('#NewClientName').val()
            }),
            contentType: 'application/json; charset=utf-8',
            success: function (reponse) {
                //alert(reponse.data.model.Id);
                alert("Database created");
            },
            error: function (err) {
                alert(err);
            }
        });
    }

Answers


The other option I would see is adding the validation data attributes manually to the html element. By this way you can avoid duplicating the error messages and other properties in both server and client side.

For ex.

@Html.TextBox("NoOfJoinees", "", new 
{ 
   size = 5,  
   data_val_required="No. of joinees is required",
   data_val_number = "The field No. of joinees must be a number.",
   data_val_range = "No. of joinees should be minimum 2 and not more than 10",
   data_val_range_max="10",
   data_val_range_min="2"
})

In the above textbox I've added three types of validations: required, type and range so easily by adding the data attributes. The unobtrusive validation library shipped by microsoft will take care of the rest.

You should read the error messages and other constants from a single place. So you don't need to replicate them when you are doing the validation at the server-side.


You could use jQuery.validate and use some of the built in validation methods. jQuery.validate

Though might be overkill for what your doing and would still require you to do server side validation.


You can still have a view model just to set validation rules and then use some unobtrusive javascript to catch for form submission to do your ajax post.

ViewModel

public class YouViewModel
{
    [DisplayName("Client name")]
    [Required()]
    public string NewClientName { get; set; }

    [DisplayName("Client id")]
    [StringLength(3, MinimumLength = 3, ErrorMessage = "{0} must be 3 characters")]
    public string NewClientId { get; set; }
}

Controller

public ActionResult YourAction()
{
    return View() //Note that you don't even need to pass a view model to the view
}

View

@model Namespace.YouViewModel

@using (Html.BeginForm())
{
    <div class="form-body">
        @Html.ValidationSummary()

        <div class="control-group">
            @Html.LabelFor(x => x.NewClientName )
            @Html.TextBoxFor(x => x.NewClientName , new { @class = "span3" })
        </div>

        <div class="control-group">
            @Html.LabelFor(x => x.NewClientId )
            @Html.PasswordFor(x => x.NewClientId , new { @class = "span3" })
        </div>
    </div>
}

Need Your Help

Which package manager to use with ASP.NET 5 (ASP.NET Core 1.0)

npm visual-studio-2015 nuget asp.net-core bower

I have a brand new asp.net 5 (soon to be re-branded ASP.NET Core 1.0), MVC 6 project and I want to add the angularjs package, as far as I can tell, there are 3 different methods 'built in' to Studi...

Cannot get python scripting working under WSH

python pywin32 wsh

I'm trying to get WSH to run Python .pys scripts and I'm hitting a wall - I've tried this on two machines now, W7x64 and Server2012, same result both time, cscript always comes back with: