ASP.NET MVC 5 Form Validation using jQuery and Bootstrap without Model class-VBForums
Results 1 to 1 of 1

Thread: ASP.NET MVC 5 Form Validation using jQuery and Bootstrap without Model class

  1. #1

    Thread Starter
    Frenzied Member KGComputers's Avatar
    Join Date
    Dec 2005
    Location
    Cebu, PH
    Posts
    1,890

    ASP.NET MVC 5 Form Validation using jQuery and Bootstrap without Model class

    Hi all,

    The steps below illustrate on how to validate an MVC form using
    jQuery and Bootstrap without a model class. I already have a C# version
    for this application.


    Create an ASP.NET MVC 5 Project in VB.NET and add codes for each file.


    1. controllers\HomeController.vb


    Code:
       Public Class HomeController
        Inherits System.Web.Mvc.Controller
    
    
        Function Index() As ActionResult
            Return View()
        End Function
    
    
        <HttpPost>
        Function Index(form As FormCollection) As ActionResult
    
    
            ' replace with database operation. for now using a registration success view.
            If form IsNot Nothing Then
                Return RedirectToAction("RegistrationSuccess")
            End If
    
    
            Return View()
    
    
        End Function
    
    
        <HttpPost>
        Function EmailExists(email As String) As JsonResult
    
    
            ' replace sample code with database checking of email.
            ' check existing email
            Return Json(Not String.Equals(email, "testing@mail.ph", StringComparison.OrdinalIgnoreCase))
        End Function
    
    
        Function RegistrationSuccess() As ActionResult
            Return View()
        End Function
       End Class
    2. views\home\Index.vbhtml (HTML Markup)
    Code:
       <div class="container">
            <div class="row">
                @Html.AntiForgeryToken()
                @Using Html.BeginForm("Index", "Home", FormMethod.Post, New With {.id = "frmInput", .class = "form-horizontal"})
                    @<div class="form-group has-feedback">
                        <label for="fname" class="control-label col-md-3">First Name:</label>
                        <div class="col-md-9">
                            <input type="text" name="fname" id="fname" class="form-control" placeholder="Enter first name" />
                            <span class="glyphicon form-control-feedback" id="fname1"/>
                        </div>
                    </div>            
                    @<div class="form-group has-feedback">
                        <label for="mname" class="control-label col-md-3">Middle Name:</label>
                        <div class="col-md-9">
                            <input type="text" name="mname" id="mname" class="form-control" placeholder="Enter middle name" />
                            <span class="glyphicon form-control-feedback" id="mname1"></span>
                        </div>
                    </div>
                    @<div class="form-group has-feedback">
                        <label for="lname" class="control-label col-md-3">Last Name:</label>
                        <div class="col-md-9">
                            <input type="text" name="lname" id="lname" class="form-control" placeholder="Enter last name" />
                            <span class="glyphicon form-control-feedback" id="lname1"></span>
                        </div>
                    </div>
                    @<div class="form-group has-feedback">
                        <label for="email" class="control-label col-md-3">Email Address:</label>
                        <div class="col-md-9">
                            <input type="email" name="email" id="email" class="form-control" placeholder="Enter email" />
                            <span class="glyphicon form-control-feedback" id="email1"></span>
                        </div>
                    </div>
                    @<div class="form-group has-feedback">
                        <label for="password" class="control-label col-md-3">Password:</label>
                        <div class="col-md-9">
                            <input type="password" name="password" id="password" class="form-control" placeholder="Enter password" />
                            <span class="glyphicon form-control-feedback" id="password1"></span>
                        </div>
                    </div>
                    @<div class="form-group has-feedback">
                        <label for="confirm_password" class="control-label col-md-3">Confirm Password:</label>
                        <div class="col-md-9">
                            <input type="password" name="confirm_password" id="confirm_password" class="form-control" placeholder="Confirm password" />
                            <span class="glyphicon form-control-feedback" id="confirm_password1"></span>
                        </div>
                    </div>
                    @<div class="form-group">
                        <div class="col-sm-offset-3 col-md-9">
                            <input type="submit" class="btn btn-primary" value="Register">
                            <button type="button" class="btn">Cancel</button>
                        </div>
                    </div>
    
    
                End Using
            </div>
        </div>

    3. views\home\RegistrationSuccess.vbhtml
    - Add this view based from RegistrationSuccess() method in HomeController.vb
    - successful registration page.
    Code:
                @Code
                ViewData("Title") = "RegistrationSuccess"
                Layout = "~/Views/Shared/_Layout.vbhtml"
                End Code
    
    
            <h2>Registration Success</h2>
    4. Content\Site.css
    - add new style for glyphicons. by default, the input controls have 280px max-width.
    Code:
             /* added style for icon */
            .glyphicon.form-control-feedback{
                left: 260px; 
            }
    5. BundleConfig.vb
    - bundle external javascript file FormValidation.js
    Code:
          Public Sub RegisterBundles(ByVal bundles As BundleCollection)
    
    
                bundles.Add(New ScriptBundle("~/bundles/jquery").Include(
                            "~/Scripts/jquery-{version}.js"))
    
    
                ' individual bundling of validate and unobtrusive
                bundles.Add(New ScriptBundle("~/bundles/jqueryval").Include(
                            "~/Scripts/jquery.validate.min.js"))
    
    
                bundles.Add(New ScriptBundle("~/bundles/jqueryunobtrusive").Include(
                            "~/Scripts/jquery.validate.unobtrusive.min.js"))
    
    
                ' Use the development version of Modernizr to develop with and learn from. Then, when you're
                ' ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
                bundles.Add(New ScriptBundle("~/bundles/modernizr").Include(
                            "~/Scripts/modernizr-*"))
    
    
                bundles.Add(New ScriptBundle("~/bundles/bootstrap").Include(
                          "~/Scripts/bootstrap.js",
                          "~/Scripts/respond.js"))
    
    
                bundles.Add(New StyleBundle("~/Content/css").Include(
                          "~/Content/bootstrap.css",
                          "~/Content/site.css"))
                
                'bundle FormValidation.js
                bundles.Add(New ScriptBundle("~/bundles/FormValidation").Include(
                         "~/Scripts/FormValidation.js"))
    
            End Sub
    6. _Layout.vbhtml
    - render the scripts and styles in this order.
    Code:
        <title>@ViewBag.Title - My ASP.NET Application</title>
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/bootstrap")
        @Scripts.Render("~/bundles/jqueryval")
        @Scripts.Render("~/bundles/FormValidation")
        @Scripts.Render("~/bundles/jqueryunobtrusive")
        @Scripts.Render("~/bundles/modernizr")
    7. Scripts\FormValidation.js
    - Add this js file under Scripts folder
    - includes remote validation feature for checking existing emails.
    Code:
       //bootstrap styling 3.x 
            $(function () {
    
    
                $("#frmInput").validate({
                    submitHandler: function (form) {
                        //submit once validation rules are met
                        form.submit();
                    },
                    rules: {
                        fname: {
                            minlength: 3,
                            maxlength: 15,
                            required: true
                        },
                        mname: {
                            minlength: 3,
                            maxlength: 15,
                            required: true
                        },
                        lname: {
                            minlength: 3,
                            maxlength: 15,
                            required: true
                        },
                        password: {
                            required: true,
                            minlength: 6
                        },
                        confirm_password: {
                            required: true,
                            minlength: 6,
                            equalTo: "#password"
                        },
                        email: {
                            required: true,
                            email: true,
                            remote: {
                                url: "/Home/EmailExists",
                                type: "post",
                                data: {
                                    email: function () {
                                        return $('#email').val();
                                    }
                                }
                            }
                        }
                    },
                    messages: {
                        email: {
                            remote: "Email already in use!"
                        }
                    },
                    highlight: function (element) {
                        var id_attr = "#" + $(element).attr("id") + "1";
                        $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
                        $(id_attr).removeClass('glyphicon-ok').addClass('glyphicon-remove');
                    },
                    unhighlight: function (element) {
                        var id_attr = "#" + $(element).attr("id") + "1";
                        $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
                        $(id_attr).removeClass('glyphicon-remove').addClass('glyphicon-ok');
                    },
                    errorElement: 'span',
                    errorClass: 'help-block',
                    errorPlacement: function (error, element) {
                        if (element.length) {
                            error.insertAfter(element);
                        } else {
                            error.insertAfter(element);
                        }
                    }
                });
            });
    8. Replace bootstrap.css and bootstrap.min.css files in Content folder with version 3.3.6. Since
    the default version of these bootstrap css files is 3.0. See attached file.


    Name:  ExistingEmail.jpg
Views: 4598
Size:  20.9 KBName:  Invalid Form.jpg
Views: 4058
Size:  20.3 KBName:  ValidForm.jpg
Views: 3931
Size:  22.6 KB

    Entire source code at github MVCFormValidationJQueryValidateVB

    That's it..KGC :-)
    Attached Files Attached Files
    Last edited by KGComputers; Apr 14th, 2017 at 01:17 AM. Reason: added github link
    CodeBank: VB.NET & C#.NET | ASP.NET
    Programming: C# | VB.NET
    Blogs: My Blog | GitHub Repo | ASP Snippets | CodeASP.net
    ___________________________________________________________________________________

    Rating someone's post is a way of saying Thanks...

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width

Survey posted by VBForums.