I have problem validating one field at client side, Here is my code:
Model:
public class Registration
{
public int Id { get; set; }
[IsUserExistAttribute(ErrorMessage = "Email already exists!")]
[EmailAddress(ErrorMessage = "Please enter valid Email")]
[Required(ErrorMessage = "Email is required")]
public string Email
{
get; set;
}
[MustBeTrue(ErrorMessage = "Please Accept the Terms & Conditions")]
public bool TermsAndConditions { get; set; }
}
ValidationAttribute:
public class IsUserExistAttribute : ValidationAttribute,IClientValidatable
{
public override bool IsValid(object email)
{
DemoDbContext demoContext=new DemoDbContext();
string emailString = Convert.ToString(email);
if (demoContext.Registrations.Any(a=>a.Email.Contains(emailString)))
{
return false;
}
return true;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = this.ErrorMessage,
ValidationType = "emailvalidate"
};
}
}
View:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Registration</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.TermsAndConditions, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
@Html.EditorFor(model => model.TermsAndConditions)
@Html.ValidationMessageFor(model => model.TermsAndConditions, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
Everthing upto this works fine, But my question is This IsUserExistAttribute doesn't validate it on client side, on server side it validates and give the message like Email already exists!
But, I want it to validate client side too. So, what is the good way to achieve this? Other approach is also welcome :)
I tried something like this seems no success:
$.validator.addMethod("emailvalidate", function (value, element) {
var is_valid = false;
$.ajax({
// as before...
async: false,
success: function (data) {
is_valid = data === 'True';
}
});
return is_valid;
}, "Username not available.");