Srb1313711
Srb1313711

Reputation: 2047

How to get custom validator to validate client side?

In my Mvc project I have this model:

namespace CameraWebApp.Models

    public class Images
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ImageId { get; set; }
        [Required(ErrorMessage="Please enter your first name")]
        public string SubmitterFirstName { get; set; }
        [Required(ErrorMessage = "Please enter your surname name")]
        public string SubmitterLastName { get; set; }
        [ExistingFileName]
        public string NameOfImage { get; set; }
        [StringLength(140, ErrorMessage="Please reduce the length of your description to below 140 characters")]
        [DataType(DataType.MultilineText)]
        public string DescriptionOfImage { get; set; }
        public string ImagePath { get; set; }
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public DateTime DateAdded { get; set; }
    }

As you can see the NameOfImage property has the attribute [ExistingFileName] which is a custom validator, the code for this validator is below:

//Overiding isValid to make a custom Validator
protected override System.ComponentModel.DataAnnotations.ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext)
{
    if (value!=null)
    {
        string fileName = value.ToString();
        if (FileExists(fileName))
        {
            //If the file exists use default error message or the one passed in if there is one
            return new ValidationResult(ExistingImageErrorMessage ?? defaultExistingImage);
        }
        else
        {
            return ValidationResult.Success;
        }  
    }
    else
    {
        //If theres no value passed in then use error message or default if none is passed
        return new ValidationResult(ErrorMessage ?? DefaultErrorMessage);
    }
}

bool FileExists(string fileName)
{
    bool exists = false;
    //A list is passed all the images
    List<Images> images = cameraRepo.getAllImages().ToList();
    //Loops through every image checking if the name already exists
    foreach (var image in images)
    {
        if (image.NameOfImage==fileName)
        {
            exists = true;
            break;
        }
    }
    return exists;
}

Each of the previous properties are being validated Client Side in the code below:

@using (Html.BeginForm())
{
<div id="errorMessages">
@Html.ValidationSummary(false)
</div>
<label>base64 image:</label>
<input id="imageToForm" type="text" name="imgEncoded"/>  
<label>First Name</label>
@Html.EditorFor(model => model.SubmitterFirstName)
<label>Last Name</label>
@Html.EditorFor(model => model.SubmitterLastName)
<label>Name of Image</label>
@Html.EditorFor(model => model.NameOfImage)
<label>Image Description</label>
@Html.EditorFor(model => model.DescriptionOfImage)
<input type=button id="button"value=" Camera button"/>
<input type="submit" value="Click this when your happy with your photo"/>
}
</div>
@Html.ActionLink("gfd!!", "DisplayLatest")
<script src="@Url.Content("~/Scripts/LiveVideoCapture.js")" type="text/javascript"></script>

All validation works Client side except my Custom validation [ExisitingFileName] and I have no idea why? Does anyone know why this might be? Thanks in advance!

Upvotes: 0

Views: 616

Answers (2)

David Colwell
David Colwell

Reputation: 2590

When validating on the client side, you need to implement IClientValidateable. This requires you to write client side validation code (javascript) and server side validation code (C#)

http://forums.asp.net/t/1850838.aspx/1

This post is also helpful
http://odetocode.com/Blogs/scott/archive/2011/02/22/custom-data-annotation-validator-part-ii-client-code.aspx

Upvotes: 1

user2572030
user2572030

Reputation: 230

Since it is a custom validation, c# mvc cannot generate a client-side validation: you'll have to implement your own custom client-side validation for this field (using Javascript). In it you may want to use AJAX to call a server method to check if filename already exists.

You can also try to use remote validation, which seems to be simpler: http://msdn.microsoft.com/en-us/library/ff398048(VS.100).aspx

Upvotes: 2

Related Questions