0

I wrote a form validation code in jquery having following fields and their conditions

1.Name-Min 3 characters,max 25 chars and must follow the pattern specified in code

2.Address- max 250 chars and follow specific pattern

3.State-must be selected

4.Country-must be selected

5.Phone number-must be 10 chars and only numerical input is allowed

6.Email-must follow the pattern of entering email

NOTE: ALL FIELDS ARE REQUIRED

HTML file (named as "htmlForm.html")

    <html>

    <head>
        <title>Form Validation Using JQuery</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <link rel="stylesheet" href="./formcss.css">
        <link href="https://fonts.googleapis.com/css?family=Bitter|Josefin Sans|Lobster|Exo" rel="stylesheet">
        <script src="./jQueryValidation.js " type='text/javascript'></script>
    </head>

    <body>
        <div class="container">
            <div class="col-lg-3"></div>
            <div class="col-lg-4">
                <div class="well">
                    <legend style="align-items: center;font-size:27px;" class="head">User Form</legend>
                    <form name="userform" id="userform">
                        <div class="row">
                            <div class="col-lg-3">
                                <label> Name:</label>
                            </div>
                            <div class="col-lg-4">
                                <input id="txtName" type="text" minlength="3" maxlength="25" required/>
                            </div>
                            <div class="col-lg-5">
                                <a style="text-decoration:none;" id="nameError"></a>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-lg-3">
                                <label>Address:</label>
                            </div>
                            <div class="col-lg-4">
                                <textarea id="txtareaAddress" required /></textarea>
                            </div>
                            <div class="col-lg-55">
                                <a style="text-decoration:none;" id="addressError"></a>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-lg-3">
                                <label> State:</label>
                            </div>
                            <div class="col-lg-4">
                                <select id="ddlState" class="ddlState" required>
                                                <option value=""></option>
                                                <option value="AP">Andhra Pradesh</option>
                                                <option value="KN">Karnataka</option>
                                                <option value="KE">Kerala</option>
                                                <option value="TN">Tamilnadu</option>
                                            </select>
                            </div>
                            <div class="col-lg-5">
                                <a style="text-decoration:none;" id="stateError"></a>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-lg-3">
                                <label>Country:</label>
                            </div>
                            <div class="col-lg-4">
                                <select id="ddlCountry" class="ddlCountry" required>
                                                    <option value=""></option>
                                                    <option value="BA">Bangladesh</option>
                                                    <option value="IN">India</option>
                                                    <option value="PA">Pakistan</option>
                                                    <option value="SR">Sri lanka</option>
                                                </select>
                            </div>
                            <div class="col-lg-5">
                                <a style="text-decoration:none;" id="countryError"></a>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-lg-3">
                                <label>Phone:</label>
                            </div>
                            <div class="col-lg-4">
                                <input type="tel" id="txtPhone" maxlength="10" required>
                            </div>
                            <div class="col-lg-5">
                                <a style="text-decoration:none;" id="phoneError"></a>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-lg-3">
                                <label>Email:</label>
                            </div>
                            <div class="col-lg-4">
                                <input type="email" class="txtEmail" id="txtEmail" required>
                            </div>
                            <div class="col-lg-5">
                                <a style="text-decoration:none;" id="emailError"></a>
                            </div>
                        </div>


                        <div class="row">
                            <div class="col-lg-3">
                                <label></label>
                            </div>
                            <div class="col-lg-6">
                                <input type="submit" id="btnSubmit" class="btn btn-sm btn-success" value="Submit">

                                <input type="submit " id="btnReset " class="btn btn-sm btn-danger " value="Reset " onclick="history.go(0) ">
                            </div>
                            <div class="col-lg-3 ">

                            </div>
                        </div>



                    </form>
                </div>
            </div>
            <div class="col-lg-3 "></div>
        </div>


    </body>

    </html>

JQUERY Validation form (named as "jQueryValidation.js" )

        $(document).ready(function() {

            $("#btnSubmit").click(function() {

                var name = $("#txtName").val();
                var patternName = /^([a-zA-Z _-]+)$/.test(name);
                alert("name:" + patternName);
                if (name.length == 0) {
                    $("#nameError").html("Name is required");
                    $("#txtName").css("border-color", "red");
                    $("#txtName").css("border-width", "1.5px");
                    $("#nameError").css("font-size", "12px");

                } else if (name.length < 3) {
                    $("#nameError").html("<p>Name must be within 3 - 25 characters</p>");
                    $("#txtName").css("border-color", "red");
                    $("#txtName").css("border-width", "1.5px");
                    $("#nameError").css("font-size", "12px");

                } else if (name.length > 25) {
                    $("#nameError").html("<p>Name must be within 3 - 25 characters</p>");
                    $("#txtName").css("border-color", "red");
                    $("#txtName").css("border-width", "1.5px");
                    $("#nameError").css("font-size", "12px");

                } else if (patternName === false) {
                    $("#nameError").html("<p>Error in name format</p>");
                    $("#txtName").css("border-color", "red");
                    $("#txtName").css("border-width", "1.5px");
                    $("#nameError").css("font-size", "12px");
                } else {
                    $("#nameError").html("");
                    $("#txtName").css("border-width", "0px");

                }



                var address = $("#txtareaAddress").val();
                var patternAddress = /^([a-zA-Z0-9]+)$/.test(address);
                alert("address:" + patternAddress);

                if (address.length == 0) {
                    $("#addressError").html("<p>Address is required</p>");
                    $("#txtareaAddress").css("border-color", "red");
                    $("#txtareaAddress").css("border-width", "1.5px");
                    $("#addressError").css("font-size", "12px");


                } else if (address.length > 250) {
                    $("#addressError").html("<p>Address must be within 250 characters</p>");
                    $("#txtareaAddress").css("border-color", "red");
                    $("#txtareaAddress").css("border-width", "1.5px");
                    $("#addressError").css("font-size", "12px");

                } else if (patternAddress === false) {
                    $("#addressError").html("<p>Error in address format</p>");
                    $("#txtareaAddress").css("border-color", "red");
                    $("#txtareaAddress").css("border-width", "1.5px");
                    $("#addressError").css("font-size", "12px");
                } else {
                    $("#addressError").html("");
                    $("#txtareaAddress").css("border-width", "0px");

                }



                var state = $("#ddlState").val();
                if (state === "") {
                    $("#stateError").html("<p>State is required</p>");
                    $("#ddlState").css("border-color", "red");
                    $("#ddlState").css("border-width", "1.5px");
                    $("#stateError").css("font-size", "12px");
                } else {
                    $("#stateError").html("");
                    $("#ddlState").css("border-width", "0px");

                }




                var country = $("#ddlCountry").val();
                if (country === "") {
                    $("#countryError").html("<p>Country is required</p>");
                    $("#ddlCountry").css("border-color", "red");
                    $("#ddlCountry").css("border-width", "1.5px");
                    $("#countryError").css("font-size", "12px");
                } else {
                    $("#countryError").html("");
                    $("#ddlCountry").css("border-width", "0px");

                }



                var phone = $("#txtPhone").val();
                var patternPhone = (/^([0-9]+)$/.test(phone));
                alert("phone:" + patternPhone);

                if (phone.length == 0) {
                    $("#phoneError").html("<p>Phone number is required</p>");
                    $("#phoneError").css("font-size", "12px");
                    $("#txtPhone").css("border-color", "red");
                    $("#txtPhone").css("border-width", "1.5px");

                } else if (phone.length > 10) {
                    $("#phoneError").html("<p>Phone number must be 10 characters</p>");
                    $("#phoneError").css("border-color", "red");
                    $("#txtPhone").val() = "";
                    $("#txtPhone").css("border-width", "1.5px");
                    $("#phoneError").css("font-size", "12px");

                } else if (phone.length < 10) {
                    $("#phoneError").html("<p>phone number must be 10 characters</p>");
                    $("#phoneError").css("border-color", "red");
                    $("#txtPhone").val() = "";
                    $("#txtPhone").css("border-width", "1.5px");
                    $("#phoneError").css("font-size", "12px");

                } else if (patternPhone === false) {
                    $("#phoneError").html("<p>Error in phone format</p>");
                    $("#phoneError").css("border-color", "red");
                    $("#txtPhone").css("border-width", "1.5px");
                    $("#txtPhone").val().reset;
                    $("#phoneError").css("font-size", "12px");
                } else {
                    $("#phoneError").html("");
                    $("#txtPhone").css("border-width", "0px");
                }



                var email = $("#txtEmail").val();
                var patternEmail = (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email));
                alert("email:" + patternEmail);


                if (email.length == 0) {
                    $("#emailError").html("<p>Email is required</p>");
                    $("#emailError").css("font-size", "12px");
                    $("#txtEmail").css("border-color", "red");
                    $("#txtEmail").css("border-width", "1.5px");
                } else if (patternEmail == false) {
                    $("#emailError").html("<p>Error in email format</p>");
                    $("#emailError").css("font-size", "12px");
                    $("#txtEmail").css("border-color", "red");
                    $("#txtEmail").css("border-width", "1.5px");

                } else {
                    $("#emailError").html("");
                    $("#txtEmail").css("border-width", "0px");

                }



            });
        });

CSS file (named as "formcss.css")

        .well {
            width: 560px;
            align-content: center;
            align-items: center;
            padding: 70px 10px;
            margin-top: 10px;
            background-color: rgb(104, 212, 185) !important;
            border-radius: 30px;
        }

        body {
            font-family: 'Bitter', serif;
            background-image: url(img.jpg);
        }

        label {
            width: 60px;
            margin-left: 60px;
        }

        input,
        label,
        textarea {
            border: 10px 0px;
            margin-bottom: 10px;
        }

Problem : The form works well for the most part . When debugging , I used to give various test cases. Mostly all cases were passed.

But when I entered all fields correctly apart from email and while I try to submit ,it shows error in email field.

I corrected the email field's entry and changed the phone number field as wrong input. This should not submit the form because phone number is not a valid input.Unfortunately, the form gets submitted .

Any alternative solution or correction in my code are welcomed!

  • 1
    Your event must be on form submit i.e. $("form").submit(function(){return false}); not on click and you need to return false if something is not correct. You can use this https://jqueryvalidation.org/ – angel.bonev Feb 14 '18 at 09:29
  • 2
    There is nothing in your code that would prevent the form from submition! You need to change the button type to `button` and add `preventDefault` to your function. This [thread](https://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false) can help you – Hamza Abdaoui Feb 14 '18 at 09:33
  • If you want an input to be required, you can do this: `` for example – MBJH Feb 14 '18 at 09:34
  • You are not handled the senario with this code. Please make a preventDefault() or return false while validation getting false. – Libin C Jacob Feb 14 '18 at 10:05
  • Correct me if I'm wrong. In Jquery code, I added a variable 'x' initialized to zero. I incremented the variable when validation of any any field is wrong. I wrote an if statement at the end of click event handling function... if (x !== 0) { e.preventDefault(); } else{ return false; } Is this code works.. The validation worked well but action is not working.. – Sundaramoorthy Anandh Feb 14 '18 at 10:59

0 Answers0