[RESOLVED]How to create a custom validation in MVC4?

Hi every body..

I already created asp.net mvc4 internet application ,and  CRUD operation is work well,but now i want to make changes in the application like validation and making display name like what i want and also i want to change the control for the image from text
to upload file to insert the image .

i created a class speaker inside model folder and i make this code

[Display(Name = "Speaker Name")]
        [Required(ErrorMessage = "Please enter the Speaker Name")]
        [DataType(DataType.Text)]
        public string Name { get; set; }

        [Display(Name = "Image")]
        [Required(ErrorMessage = "Please Enter the Image")]
        // [UIHint("Image")]
        [DataType(DataType.Upload)]
        public string Image { get; set; }

        [Display(Name = "Discription")]
        [Required(ErrorMessage = "Please Enter the Description")]
        public string Description { get; set; }

but nothing changed,i don’t know if there is any other place i should change in the application if there is, what’s it please?

and the most problem i faced is modifing the control as what i need,ex how i can customize the image and make upload file control ??

hope to get me ^_^

thanks in advance

Web Developer1

make changes in the application like validation

To perform validation, in addition to the data annotations in the mode, you need to use the validation helpers in your view. Please check this Microsoft article

Performing Simple Validation

Web Developer1

making display name like what i want

To show the display name, you should use Html.DisplayFor

Web Developer1

i want to change the control for the image from text to upload file to insert the image .

Please check the below link on how to upload image

Uploading Images in ASP.NET MVC

Thanks pprasannak for replaying ,

accourding to validation i want to perform validatiion with data annotation

 [MetadataType(typeof(SpeakerMetadata))]
    public class Speaker
    {
    }
     public partial class SpeakerMetadata
     {
[Display(Name = "Speaker Name")]          [Required(ErrorMessage = "please enter speaker name ")]          [DataType(DataType.Text)]          public string Name { getset; }
}


i added previous class in the model and when i'm trying to create new speaker this message appear 

Validation failed for one or more entities. See ‘EntityValidationErrors’ property for more details.

You have’nt mentioned your view . As per my best knowledge these changes will work on if you use EditorFor and DeisplayFor helpers in your view.   

Anupam Singh ,this is the view for creation new speaker

@model TeDxMukalla.Speaker
 
@{
    ViewBag.Title = "Create Speaker";
}
 
<h2>Create</h2>
 
@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
 
    <fieldset>
        <legend>Speaker</legend>
 
        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
 
        <div class="editor-label">
            @Html.LabelFor(model => model.Image)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Image)
            @Html.ValidationMessageFor(model => model.Image)
        </div>
 
        <div class="editor-label">
            @Html.LabelFor(model => model.Description)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Description)
            @Html.ValidationMessageFor(model => model.Description)
        </div>
 
        <p>
            <input type="submit" value="إضافة" />
        </p>
    </fieldset>
}
 
<div>
    @Html.ActionLink("Back to List", "Index")
</div>
 
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Hi,

I think the issue is in the Image validation. You have Required attribute in the
Image property and that value is null.

I suggest that you could refer to this code below to custom validation.

 

public class ValidateFileAttribute : RequiredAttribute
{
    public override bool IsValid(object value)
    {
        var file = value as HttpPostedFileBase;
        if (file == null)
        {
            return false;
        }

        if (file.ContentLength > 1 * 1024 * 1024)
        {
            return false;
        }

        try
        {
            using (var img = Image.FromStream(file.InputStream))
            {
                return img.RawFormat.Equals(ImageFormat.Png);
            }
        }
        catch { }
        return false;
    }
}
public class MyViewModel
{
    [ValidateFile(ErrorMessage = "Please select a PNG image smaller than 1MB")]
    public HttpPostedFileBase File { get; set; }
}

Best Regards

Starain

Web Developer1

Validation failed for one or more entities. See ‘EntityValidationErrors’ property for more details.

You will get this error if you pass null to a database required field. You will also get this error message for the data type mismatch. Please check the below link to get a better error message

System.Data.Entity.Validation.DbEntityValidationResult
– Validation failed for one or more entities. See ‘EntityValidationErrors’ property for more details.

Leave a Reply