locked
Simple form validation error - Returns error . $(...).valid is not a function RRS feed

  • Question

  • User-973886032 posted

    hi guys

    I am trying to create a form validation, and added the JQUERY files, but getting errors. Main code below is

       var form = $('#Add_Form');
                   // form.validate();
                    if ($('#Add_Form').valid()) {//Valid
                        alert('1   says  -' + form.valid());
                       // form.focusInvalid();
                        return false;
                          Dawn(data);
    
                    }
                    else
                    {//INVALID
                         alert('2    -' + form.valid());
                        form.focusInvalid();
                    }

    I am trying to validate and focus on the required fields in yellow below

    Here is my code

    @model Xxxx.Models.Accounts._Users_Accounts_INSERT
    
    @section scripts
        {
    
        <script>
    
    
            $(document).ready(function () {
    
                $('#Main').show();
                $('#Wait').hide();
    
    
                $('#Add_Submit').on("click", function (e) {
                    e.preventDefault();
    
                    var last_Name = $("#First_Name").val();
                    var first_Name = $("#Last_Name").val();
                    var mobile = $("#Mobile").val();
                    var Username = $("#Username").val();
    
                                    var last_Name = $('#Add_Form input[name=First_Name]').val();
                    var first_Name = $('#Add_Form input[name=Last_Name]').val();
    
                    var token = $('#Add_Form input[name="__RequestVerificationToken"]').val();
                    
                    alert(last_Name + '  ' + first_Name);
                    
                    var data = { __RequestVerificationToken: token, First_name: first_Name, Last_name: last_Name };
                    
    
                      $('#Wait').slideUp(900).show();
                            $('#Main').slideDown(900).show();
                          
                    $('#Wait2').slideDown(90).show().html('<div class="Text-Center"><br/><br/> Please wait while we update your account <br/><br/><br/> Thank you </div>');
    
                    //if ($("#Add_Form").valid())
    
                    //    ehi(data);
    
    
                    //else
                    //    validator.focusInvalid();
    
                    //return false;
    
    
                     var form = $('#Add_Form');
                   // form.validate();
                    if ($('#Add_Form').valid()) {//Valid
                        alert('1  says  -' + form.valid());
                       // form.focusInvalid();
                        return false;
                          Dawn(data);
    
                    }
                    else
                    {//INVALID
                         alert('2  says  -' + form.valid());
                        form.focusInvalid();
                    }
    
                  //  if (form.valid()) {
    
    
                    Dawn(data);
                });
    
    
                  
    
    
    
    
    
                function Dawn(data) {
    
    
                    $.ajax({
    
                        type: "POST",
                        url: "Personal",
                        dataType: 'json',
                        data: data,
    
                        success: function (message) {
    
    
                            $('#Wait2').slideDown(90).show().text('<div class="Text-Center">Thank you <br/>Your Account has been successfully updated</div>');
                             // $('#giphy').hide():
    
                        },
                        error: function (message) {
    
                            $('#Wait2').slideDown(90).show().html('<div class="Text-Center">There was an error  - Please try again</div>');
                           // $('#giphy').hide():
                        }
    
                    });
                };
    
    
    
            });
        </script>
    
       
    }
        @{
            ViewData["Title"] = "Personals";
        }
    
    
    
    
    
        <div class="container">
            <div class="col-md-12"><div class="col-md-6"><h2>Personal Details</h2> </div><div class="col-md-6 text-right">Others here</div></div>
            <div class="row border border-info ">
                <div class="col-md-3"> @await Html.PartialAsync("~/Views/Shared/Accounts_Users/_Users.cshtml")</div>
                <div class="col-md-1">
                </div>
                <div class="col-md-5 summary text-center" id="Wait">
                    <div id="Wait2"> <br />  Please wait<br /><br /></div>
                    <img src="~/images/giphy.gif" />
                </div>
                <div class="col-md-5  " id="Main" style="display:none;">
                    <form asp-action="Address_Add" id="Add_Form">
                        <br /> 
                        @Html.AntiForgeryToken()
                        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
    
                        <div class="form-group">
                            <label asp-for="Username" class="control-label">Username</label>
                            <input asp-for="Username" required class="form-control" maxlength="15" />
                            <span asp-validation-for="Username" class="text-danger"></span>
                        </div>
    
                        @*<div class="form-group ">
                <label asp-for="Title" class="control-label"></label>
                @Html.DropDownList("AddressType", new SelectList(ViewBag.Titled, "Value", "Text"), new { @class = "form-control", @style = "width: 50px;" })
                <span asp-validation-for="Title" class="text-danger"></span>
            </div>*@
    
                        <div class="form-group">
                            <label asp-for="First_Name" class="control-label">First Name</label>
                            <input asp-for="First_Name" required class="form-control" maxlength="50" />
                            <span asp-validation-for="First_Name" class="text-danger"></span>
                        </div>
    
                        <div class="form-group">
                            <label asp-for="Last_Name" class="control-label">Last Name</label>
                            <input asp-for="Last_Name" required class="form-control" maxlength="50" />
                            <span asp-validation-for="Last_Name" class="text-danger"></span>
                        </div>
    
    
                        @*<div class="form-group">
                <label asp-for="Gender" class="control-label">Gender</label>
                @Html.DropDownList("AddressType2", new SelectList(ViewBag.Gender, "Value", "Text"), new { @class = "form-control", @style = "width: 50px;" })
                <span asp-validation-for="Gender" class="text-danger"></span>
            </div>*@
    
                        <div class="form-group">
                            <label asp-for="Mobile" class="control-label">Mobile</label>
                            <input asp-for="Mobile" required class="form-control" maxlength="15" />
                            <span asp-validation-for="Mobile" class="text-danger"></span>
                        </div>
    
    
    
    
                        <br />
                        <hr />
                        <br />
                        <div class="form-group">
                            <input type="submit" id="Add_Submit" value="Go !" class="btn" />
                        </div>
                        <br />
                        <hr />
                        <br />
                    </form>
                </div>
                <div class="col-md-3"></div>
            </div>
        </div>
     

    Error message

    Personals:537 Uncaught TypeError: $(...).valid is not a function
        at HTMLInputElement.<anonymous> (Personals:537)
        at HTMLInputElement.dispatch (VM224 jquery.js:5183)
        at HTMLInputElement.elemData.handle (VM224 jquery.js:4991)

    Here is my model. i have added required fields and data annotations, But on the razor field, no data annotations appear. What is wrong here

     public class _Users_Accounts_INSERT
        {
            [Key]
            public int AccountID { get; set; }
            public Guid UniqueID { get; set; }
            public int UserID { get; set; }
    
    
            [Required(ErrorMessage = "Please enter the first name")]
            [StringLength(50, MinimumLength = 2)]
            public string First_Name { get; set; }
    
            [Required(ErrorMessage = "Please enter the last name")]
            [StringLength(50, MinimumLength = 2)]
            public string Last_Name { get; set; }
    
            [Required(ErrorMessage = "Please enter your chosen Username")]
            [StringLength(50, MinimumLength = 6)]
            public string Username { get; set; }
            public string Title { get; set; }
    
            [ForeignKey("ASPNetUsers")]
            public string ASPNetID { get; set; }
            [ForeignKey("ASPNetUsers")]
            [Display(Name = "Email Address")]
            [EmailAddress]
            [RegularExpression("^[_A-Za-z'`+-.]+([_A-Za-z0-9'+-.]+)*@([A-Za-z0-9-])+(\\.[A-Za-z0-9]+)*(\\.([A-Za-z]*){3,})$", ErrorMessage = "Enter proper email")]
            [Required]
            [DataType(DataType.EmailAddress, ErrorMessage = "The email is not valid")]
              public string Email { get; set; }
    
            [DataType(DataType.PhoneNumber)]
            [Display(Name = "Mobile Number")]
            public string Mobile { get; set; }
            public string Gender { get; set; }
            public string Account_Type { get; set; }
        }

    Even though I put email as a required field, the email value is picked up on the server side and not client side, same goes with the other fields that are not displayed on the client razor page

    Finally my layout page

    I had added the jquery.js file and the jquery.validate.unobtrusive.js both of which I have highlighted in yellow

    The jquery.validate.min.js already existed

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>@ViewData["Title"] - Xxx</title>
    
        <environment include="Development">
            <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
            <link href="~/lib/xxxx/css/main.css" rel="stylesheet" />
    
            <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha384-xBuQ/xzmlsLoJpyjoggmTEz8OWUFM0/RC5BsqQBDX2v5cMvDHcMakNTNrHIW2I5f" crossorigin="anonymous"></script>
    
    
            <script src="~/lib/jquery/dist/jquery.js"></script>
     
            <script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
            <script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"></script>
    
    
     
    
            <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
        </environment>
        <environment exclude="Development">
            <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
                  asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
                  asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute"
                  crossorigin="anonymous"
                  integrity="sha384-ggOy xT2MZw1T" />
        </environment>
        <link rel="stylesheet" href="~/css/site.css" />
        
    </head>
    <body>



              @RenderBody()
            </main>
        </div>
    
        <footer class="border-top footer text-muted">
            <div class="container">
                &copy; 2019 - Xxxx - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
            </div>
        </footer>
    
        <environment include="Development">
            <script src="~/lib/jquery/dist/jquery.js"></script>
            <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.js"></script>
        </environment>
        <environment exclude="Development">
            <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"
                    asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
                    asp-fallback-test="window.jQuery"
                    crossorigin="anonymous"
                    integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=">
            </script>
            <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"
                    asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"
                    asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
                    crossorigin="anonymous"
                    integrity="sha384-xrRywqdh3PHs8keKZN+8zzc5TX0GRTLCcmivcbNJWm2rs5C8PRhcEn3czEjhAO9o">
            </script>
        </environment>
        <script src="~/js/site.js" asp-append-version="true"></script>
    
        @RenderSection("Scripts", required: false)
    </body>
    </html>



    Thursday, July 25, 2019 10:20 AM

All replies

  • User475983607 posted

    The error generally means you are trying to use jQuery validation before jQuery validation is loaded in the browser.  Do the normal troubleshooting.  Open the browser's dev tools by pressing F12.  Look for 404 errors, console errors, and make sure jQuery validate (or the library you are using) is listed in the Network View.

    Thursday, July 25, 2019 11:06 AM
  • User-2054057000 posted

    I think your are not referencing the JS files for validation in proper manner. The correct manner is:

    1. First reference jQuery
    2. Next reference jquery.validate.js
    3. jquery.validate.unobtrusive.js

    Take help from this client side validation tutorial also. Make sure to check the console window for any mission js file error (404).

    Thursday, July 25, 2019 11:17 AM
  • User-474980206 posted
    Because you used the unobtrusive script, you need use the unobtrusive attribute syntax to define validation rules, data-val-required=“Message”. Also you need a validation summary, or field validation to display the errors.

    If you want to use jquery validation directly, than remove the unobtrusive validation, and define the validations rules, and error display methods. See docs.
    Thursday, July 25, 2019 2:09 PM
  • User-973886032 posted

    I finally got it to work.

    As it worked in my previous projects and when I stripped it down to bare html code it worked.

    I removed the Jquery include at the bottom of the _Layout page

        <environment include="Development">
            @*<script src="~/lib/jquery/dist/jquery.js"></script>*@
            <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.js"></script>
        </environment>
        <environment exclude="Development">
            <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"
                    asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
                    asp-fallback-test="window.jQuery"
                    crossorigin="anonymous"
                    integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=">
            </script>
            <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"
                    asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"
                    asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
                    crossorigin="anonymous"
                    integrity="sha3 rs5C8PRhcEn3czEjhAO9o">
            </script>
        </environment>
        <script src="~/js/site.js" asp-append-version="true"></script>
    
        @RenderSection("Scripts", required: false)
    </body>
    </html>

    Friday, July 26, 2019 4:05 AM
  • User839733648 posted

    Hi afrika,

    It seems that you have loaded two versions of jquery on your page.

    You could try to comment or remove one and it may work.

            //<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha384-xBuQ/xzmlsLoJpyjoggmTEz8OWUFM0/RC5BsqQBDX2v5cMvDHcMakNTNrHIW2I5f" crossorigin="anonymous"></script>
            <script src="~/lib/jquery/dist/jquery.js"></script>

    Reference: https://stackoverflow.com/questions/19823998/jquery-validation-error-validate-is-not-a-function

    Best Regards,

    Jenifer

    Friday, July 26, 2019 6:11 AM