Maro
Maro

Reputation: 2629

Complex Remote validation based on 2 properties

I'm trying to use custom remote validation to validate 2 properties based on one another with no success.

Action

Edit only, no insert

Properties

Both properties are free text (no dropdownlist)

Validation conditions

Code

1- Json function in the controller

public JsonResult IsFileValid(string folderName, string fileName)
    {
        if (!folderName.IsNullOrEmpty() && fileName.IsNullOrEmpty())
        {
            // FileName can be empty even if Folder name is present
            return Json(true, JsonRequestBehavior.AllowGet);
        }

        if (folderName.IsNullOrEmpty() && fileName.IsNullOrEmpty())
        {
            //FileName can be empty even if Folder name is present
            return Json(true, JsonRequestBehavior.AllowGet);
        }

        if (folderName.IsNullOrEmpty() && !fileName.IsNullOrEmpty())
        {
            //FileName can only be filled in if Folder name is present
            return Json(false, JsonRequestBehavior.AllowGet);
        }

        var Folder =
            Uow.Folders.GetAll()
                .FirstOrDefault(x => x.Name.ToLower().Trim() == folderName.Trim().ToLower());



        if (Folder != null)
        {
            // the Folder already exists, FileName name should be unique.
            return Uow.Files.GetAll()
                .Any(
                    x =>
                        x.FolderId == Folder.Id &&
                        x.fileName.Trim().ToLower() == fileName.Trim().ToLower()) ? Json(false, JsonRequestBehavior.AllowGet) : Json(false, JsonRequestBehavior.AllowGet);
        }
        // Folder name is new, in this case we can add new Folder and basked name
        return Json(true, JsonRequestBehavior.AllowGet);
    }

2- Create Custome remote attribute class

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        // When using remote attribute, we specify the controller, action and the error message. The aim of the following is to retrieve the controller, action and error message
        //using reflection.

        // first get the controller
        Type controller =
            Assembly.GetExecutingAssembly()
                .GetTypes()
                .FirstOrDefault(
                    type =>
                        type.Name.ToLower() ==
                        string.Format("{0}Controller", this.RouteData["controller"].ToString()).ToLower());
        if (controller != null)
        {
            // Get the method in the controller with
            MethodInfo action =
                controller.GetMethods()
                    .FirstOrDefault(method => method.Name.ToLower() == this.RouteData["action"].ToString().ToLower());
            if (action != null)
            {
                // create instance of the controller
                object instance = Activator.CreateInstance(controller);

                //invoke the action method of the controller, and pass the value which is the parameter of the action
                object response = action.Invoke(instance, new object[] {value});

                // because the remote validation action returns JsonResult
                var returnType = response as JsonResult;
                if (returnType != null)
                {
                    object jsonData = returnType.Data;

                    //because the jsonDate is bool
                    if (jsonData is bool)
                    {
                        // return success or the error message
                        return (bool) jsonData ? ValidationResult.Success : new ValidationResult(this.ErrorMessage);
                    }
                }
            }
        }
        return new ValidationResult(ErrorMessage);
    }

3- My viewModel class

 public class FileInViewModel
    {

        public string FolderName { get; set; }

        [RemoteValidation("IsFileValid","Home",ErrorMessage="Please select different file name")]
        public string FileName { get; set; }

        // .....
    }

Upvotes: 1

Views: 589

Answers (1)

donya
donya

Reputation: 11

See the code below:

[Remote("CheckExist", "securitylevels", AdditionalFields = "Id", ErrorMessage = "the number is Zero!")]
public int Number { get; set; }

Upvotes: 1

Related Questions