最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Validation in MVC 3 without a Model - Stack Overflow

programmeradmin0浏览0评论

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);
            }
        });
    }

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);
            }
        });
    }
Share Improve this question edited Mar 22, 2014 at 7:24 Rahul 2,3076 gold badges35 silver badges61 bronze badges asked Jun 15, 2012 at 15:58 DanDan 1222 silver badges9 bronze badges 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. – Tin Can Commented Jun 15, 2012 at 16:02
  • yes. If it doesnt validate, it shouldn't call the ajax command. – Dan Commented Jun 15, 2012 at 16:11
  • Why can't you use a model and use data annotations? – NinjaNye Commented Jun 15, 2012 at 16:16
  • As WooHoo said, you will need server-side validation then, no matter the jQuery validation. – Tin Can Commented Jun 15, 2012 at 16:17
  • 1 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$ – Doug Chamberlain Commented Jun 15, 2012 at 17:19
 |  Show 1 more comment

3 Answers 3

Reset to default 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.

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>
}
发布评论

评论列表(0)

  1. 暂无评论