Is there a way how to perform a "database" check through the Client Side Validation in MVC?

I have the following class

public class EmailCheck : ValidationAttribute,IClientValidatable
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        string sErrorMessage = "Email already exists";
        return new ValidationResult(sErrorMessage); 
    }   

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        ModelClientValidationRule validationRule = new ModelClientValidationRule();
        validationRule.ValidationType = "checkemail";
        validationRule.ErrorMessage = "Invalid Email Format";
        validationRule.ValidationParameters.Add("param", "");
        return new List<ModelClientValidationRule> { validationRule };
    }  
}

I would like the Client Side Validation to call the "IsValid" method onkeyup/lost focus as well and not just do the regular javascript checks in the "checkemail" javascript function.

The javascript function i have is the following:

//Validation for Well-Formed Email
jQuery.validator.addMethod("checkemail",
    function (value, element, param) {
        var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

        if (!emailReg.test(value))
            return false;

        return true;
    });

jQuery.validator.unobtrusive.adapters.add("checkemail", ["param"], function (options) {    
    options.rules["checkemail"] = options.params.param;
    options.messages["checkemail"] = options.message;
});

I would appreciate if anyone could guide me in the right direction or provide a tutorial of something similar.

Thanks

有帮助吗?

解决方案

In your model try to use the "Remote" attribute

http://msdn.microsoft.com/en-us/library/gg508808%28v=vs.98%29.aspx

其他提示

Rusty is correct, you need to use the Remote attribute in your model

Here is another example with complete detail only for email validation in MVC

MVC model validation for email from database in asp.net

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top