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:
[Required]
field, except it needs to get a response from the server to proceed)? This would be the best option. Ajax
call on some appropriate even (say, onChange
) and then update a div after grabbing the result? 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.