MVC 3 Razor - Trigger validation from controller

2020-08-19 02:27发布

I have to check to see if the new users email already exists in the database. The email passes all the normal validation but what if I want to trigger a special validation from the controller if the email already exists after checking it against the database?

3条回答
The star\"
2楼-- · 2020-08-19 02:40

I think what you are looking for is the RemoteAttribute.

This is a ValidationAttribute for remote validation. It works like the other validation attributes by adding model errors to your modelstate dictionary.

Check out these articles on using the RemoteAttribute:

查看更多
家丑人穷心不美
3楼-- · 2020-08-19 02:50

In controller: ModelState.AddModelError("ErrorEmail", "Error Message");

In View: @Html.ValidationMessage("ErrorEmail")

Hope this helps

查看更多
不美不萌又怎样
4楼-- · 2020-08-19 02:58

I found a way to perform conditional validation from the ViewModel. The VM class will need to implement the IValidatableObject interface.

Then add a method similar to this at the bottom of the VM:

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (validationContext == null)
            return null;

        var valResults = new List<ValidationResult>();

        if (!EmailExists))
            valResults.Add(new ValidationResult($"Email is required.", new[] { "ErrorEmail" }));

        return valResults;
    }

And of course you will need this in the View:

@Html.ValidationMessage("ErrorEmail")

Hope that helps!

查看更多
登录 后发表回答