Client side validation on button click before AJAX

2019-06-21 06:33发布

I'm using MVC 4 and I want to be able to validate a single row, from a collection of rows in a table, to ensure that the fields are entered correctly and pass validation.

The Attributes are correctly applied on the model, for example:

[Required]
[MaxLength(50)]
[MinLength(5)]
public string Name {get; set;}

Now, on the client side - how do I enable client side validation before calling an AJAX method?

To add more complications - I have a button where you can dynamically add a row to the table, fill out fields and finally hit the update button, which will do a POST via ajax. But before this post, I want to validate that particular row on client side.

how can I do this?

thank you

1条回答
该账号已被封号
2楼-- · 2019-06-21 06:36

As long as you're implementing the validation helpers in your View, this is actually really simple.

var form = $('#form');
$.validator.unobtrusive.parse(form);
form.validate();

if (form.valid()) {
    .... ajax stuff
}

Call the above before initiating the http request and it will make sure that your form is validated.

查看更多
登录 后发表回答