Validation in MVC 3 without a Model
Asked Answered
L

3

4

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);
            }
        });
    }
Lectureship answered 15/6, 2012 at 15:58 Comment(6)
Does the validation affect if it should be stored to your db? If so Javascript is nice, but you need to validate server-side. Bypassing client-side validation is pretty easy.Brooke
yes. If it doesnt validate, it shouldn't call the ajax command.Lectureship
Why can't you use a model and use data annotations?Troublous
As WooHoo said, you will need server-side validation then, no matter the jQuery validation.Brooke
Is it really MVC if you don't have a Model? What's so wrong with just creating a Model, Even if there isn't a data backend for the model? It still allows you to leverage the default Model Binders to handle your request data. My .02$Bohunk
@Lectureship i forget one point before posting the answer you want to alert the error sigh!Gunpoint
G
14

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.

Gunpoint answered 15/6, 2012 at 16:54 Comment(1)
thank you so much, i modified this little and this met my requirement check thisCinelli
S
2

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.

Seabury answered 15/6, 2012 at 16:6 Comment(0)
J
2

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>
}
Jemimah answered 15/6, 2012 at 16:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.