0

I have added all the required things regarding to client side validation but validation is not working.

Please help me find which thing I have missed or what I am doing wrong.

I have added all the required thing as below:

BundleConfig.cs

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                    "~/Scripts/jquery-{version}.js"));

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.validate*"));


bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                  "~/Scripts/bootstrap.min.js",
                  "~/Scripts/umd/popper.min.js"));

View:

@model WebApplication1.Areas.Users.Models.MyViewModel
<div>
    <!-- Modal content-->
    <div class="modal-content">
        @using (Html.BeginForm("detail", "mycontroller", null, FormMethod.Post, new { @Id="myForm", @class = "form-horizontal" }))
        {
        <!-- Modal Header -->
            <div class="modal-header">
                <h4 class="modal-title">Unit Type</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
        <!-- Modal body -->
            <div class="modal-body">
                <div class="full-wdth clearfix otp-section">
                    @Html.AntiForgeryToken()
                    @Html.ValidationSummary(true)
                    @Html.HiddenFor(model => model.Id)
                    <div id="validation-summary"></div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.Name, new { @class = "main-label requiredasterisk" })

                        @Html.TextBoxFor(model => model.Name, htmlAttributes: new { @class = "form-control form-control-sm", placeholder = "Name", maxlength = "50" })
                        @Html.ValidationMessageFor(model => model.Name)
                    </div>
                </div>
            </div>
        <!-- Modal footer -->
            <div class="modal-footer customMargin">
                <button data-dismiss="modal" id="btn-cancel" class="btn btn-default" type="button">Cancel</button>
                <button class="btn btn-primary" id="btn-submit" type="submit">
                    Submit
                </button>
            </div>
        }
    </div>
</div>

Layout.cshtml

@Scripts.Render("~/bundles/jquery", "~/bundles/jqueryval", "~/bundles/bootstrap")

WebConfig.cs:

<appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

on browser HTML page showing the JS files:

<script src="/Scripts/jquery-3.3.1.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="/Scripts/bootstrap.min.js"></script>
<script src="/Scripts/umd/popper.min.js"></script>
<script src="/Scripts/perfect-scrollbar/perfect-scrollbar.min.js"></script>
<script src="/Scripts/XXXXXX.min.js"></script>
<script src="/Scripts/XXXXXXXX.js"></script>

Before submit on browser the HTML code:

<div class="form-group">
   <label class="main-label requiredasterisk" for="Name">Name</label>    
   <input class="form-control form-control-sm" data-val="true" data-val-required="The name is required" id="Name" maxlength="50" name="Name" placeholder="Name" type="text" value="">
   <span class="field-validation-valid" data-valmsg-for="Name" data-valmsg-replace="true"></span>
</div>

After press submit button:

<div class="form-group">
  <label class="main-label requiredasterisk" for="Name">Name</label>    
  <input class="form-control form-control-sm valid" data-val="true" data-val-required="The name is required" id="Name" maxlength="50" name="Name" placeholder="Name" type="text" value="">
   <span class="field-validation-valid" data-valmsg-for="Name" data-valmsg-replace="true"></span>
</div>

MyViewModel.cs:

public class MyViewModel
{            
    /// <summary>
    /// Id 
    /// </summary>
    public int Id { get; set; }

    /// <summary>
    /// name
    /// </summary>
    [Required(ErrorMessage = "The name is required")]
    [Display(Name = "Name")]
    public string Name { get; set; }    
}

Jquery:

var BindFormSubmit = function (formControl, options) {
    "use strict";
    var settings = {};
    settings = $.extend({}, settings, options);
    formControl.validate(settings.validateSettings);
    formControl.submit(function (e) {
        var formdata = new FormData();         
        $.each(formControl.serializeArray(), function (i, item) {
            formdata.append(item.name, item.value);
        });


        var submitBtn = formControl.find(':submit');
        if (formControl.validate().valid()) {             
            $.ajax(formControl.attr("action"), {
                type: "POST",
                data: formdata,
                contentType: false,
                processData: false,
                success: function (result) {

                    //on success
                }
            });
        }
        e.preventDefault();
    });
    return formControl;
};


BindFormSubmit($("#myForm"), { updateTargetId: "validation-summary" });
4
  • How are you rendering the modal? Are you using ajax? If you are then have a look at this post stackoverflow.com/questions/23930787/… Commented Mar 19, 2019 at 20:35
  • Did you checked that you have the Nuget package installed? Commented Mar 19, 2019 at 22:59
  • @JonathanOrtega I have created default template application with auth can you please let me know which additional Nuget packages required to validate the form? Commented Mar 20, 2019 at 5:15
  • @KevDevMan Yeah, I'm validating the form using formElement.validate().valid() and also formElement.valid() but in both case it's return true (mean as valid form). Commented Mar 20, 2019 at 5:18

1 Answer 1

1

All things are correct except the binding the client side submit event with validation setting.

Because

formControl.validate(settings.validateSettings);

is overriding the validation and preventing the default MVC validation so, I have to comment the above code statement as below and it will work perfectly.

var BindFormSubmit = function (formControl, options) {
    "use strict";
    var settings = {};
    settings = $.extend({}, settings, options);
    //formControl.validate(settings.validateSettings);
    formControl.submit(function (e) {
        var formdata = new FormData();         
        $.each(formControl.serializeArray(), function (i, item) {
            formdata.append(item.name, item.value);
        });


        var submitBtn = formControl.find(':submit');
        if (formControl.validate().valid()) {             
            $.ajax(formControl.attr("action"), {
                type: "POST",
                data: formdata,
                contentType: false,
                processData: false,
                success: function (result) {

                    //on success
                }
            });
        }
        e.preventDefault();
    });
    return formControl;
};


BindFormSubmit($("#myForm"), { updateTargetId: "validation-summary" });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.