简体   繁体   中英

Is there any “built-in” way to do field-specific, server-side AJAX validation in MVC5? If not, are there any helpers that can assist with this?

I often find myself wanting to validate individual form fields on the fly in MVC5 and while I like the DataAnnotations I do not think they offer a way to perform server-side validation out of the box.

I realize that the validation will be performed on submission anyway but there are certain fields, like username , which the user should be able to see on-the-fly whether they are valid or not. So I keep on writing jQuery/Javascript code to check these fields with $.ajax or similar, and it's a lot of boilerplate code writing. IE, after the appropriate event (input changed) is fired, the client makes a call to the server, then updates a validation placeholder to the right of the field with a checkmark if valid and a bad image if invalid.

What bothers me even more is that there is no static type-checking, so I won't know about any egregious syntax errors (ie mis-spelled div id's) until runtime.

I would like to know:

  1. Is it possible to write a custom attribute that would call the server on submit (just like it would for, say, a [Required] field, except it needs to get a response from the server to proceed)? This would be the best option.
  2. Are there any built-in helpers that can make an Ajax call on some appropriate even (say, onChange ) and then update a div after grabbing the result?
  3. If you are an ASP.NET MVC developer, how have you tackled this problem in the past? I don't want to keep on writing boilerplate javascript. I know javascript is unavoidable, but this seems like a generic enough problem that it would be possible to write such a helper.

Thanks in advance for any and all advice.

You can use the RemoteAttribute .

You specify a method on the controller to be called every time the value changes,and return true if its valid,or error messagee if its not.

In your model:

[Remote("IsUserNameUnique", "User")]
public string UserName { get; set; }

Controller:

public class UserController : Controller
{
    public JsonResult IsUserNameUnique(string UserName)
    {
       if(isUnique(UserName))
          return Json(true,JsonRequestBehavior.AllowGet);
       else 
          retuen Json("Username is taken.",JsonRequestBehavior.AllowGet)
    }
}

And if your view you just put

@Html.ValidationMessageFor(model=>model.UserName)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM