Question

I have created custom validation attribute

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public sealed class ValidateDublicateNameAttribute : ValidationAttribute, IClientValidatable
    {
        private const string _defaultErrorMessage = "Library with title {0} is already exist";
        private UnitOfWork unit = new UnitOfWork();

        public ValidateDublicateNameAttribute()
            : base(_defaultErrorMessage)
        {
        }
        public override s

tring FormatErrorMessage(string name) { return String.Format(ErrorMessageString, name); }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        string valueAsString = value as string;
        ValidationResult result = ValidationResult.Success;
        if (String.IsNullOrEmpty(valueAsString))
        {
            if (unit.ResourceSrvc.GetLibraryByTitle(valueAsString) != null)
            {
                result = new ValidationResult(String.Format(_defaultErrorMessage,value));
            }
        }
        else
        {
            result = new ValidationResult("Title cant be empty or null");
        }
        return result;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = this.ErrorMessage,
            ValidationType = "dublicatename",
        };
        yield return rule;
    }
}

and have decorated my model using it

public class ResourceLibraryModel
{
    public Guid LibraryId { get; set; }
    [Required]
    [ValidateDublicateName(ErrorMessage="title cant dublicate")]
    public string Title { get; set; }
}

in client side I have

<script src="/Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {

        $.validator.addMethod("dublicatename", function (value, element, params) {
            alert("test");
        });

    });
</script>

I have not any validation parameters and didn't write $.validator.unobtrusive.adapters.add(....)

Server side validation works perfectly, but client side does not work.

Any ideas?

and this is view

     @using (Ajax.BeginForm("CreateLibrary", "Resource", new AjaxOptions { OnSuccess = "RequestSucceeded"}))
        {
            @Html.ValidationSummary(true, "Account creation was unsuccessful. Please correct the errors and try again.")
                <div>
                    @*<div style="margin-bottom:15px">
                        <label><b>Library information:</b></label>
                    </div>*@

                    <div class="editor-field">
                        @Html.TextBoxFor(m => m.Title, new { @class = "logon-field" })
                        @Html.ValidationMessageFor(m => m.Title)
                    </div>
                    <div class="editor-label">
                        @Html.LabelFor(m => m.Title)
                    </div>
                 </div>
}
Was it helpful?

Solution

I think the problem is that jquery.validate.min.js must be loaded after your javascript code...

OTHER TIPS

Just a guess but have you enabled client-side validation in your Web.config file?

 <appSettings>
  <add key="ClientValidationEnabled" value="true"/> 
  <add key="UnobtrusiveJavaScriptEnabled" value="true"/> 
 </appSettings>

If so follow the Enabling Client-Side Validation section in this link: http://www.asp.net/mvc/tutorials/creating-a-mvc-3-application-with-razor-and-unobtrusive-javascript

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top