Why won't my validation javascript works in html5 bootstrap?

I have this old javascript that works but now I need to change the layout to Bootstrap and I sort of copy it over. But, it is not working in html5 bootstrap layout!

Hope someone can tell me what is wrong.

<%@ page contentType="text/html; charset=UTF-8"%>
<html lang="en">

    <head>
        <script src="https://www.google.com/recaptcha/api.js" async defer></script>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="">
        <meta name="author" content="">

        <title></title>

        <!-- Bootstrap Core CSS -->
        <link href="BootStrap/css/bootstrap.min.css" rel="stylesheet">

        <!-- Custom CSS -->
        <link href="BootStrap/css/modern-business.css" rel="stylesheet">

        <!-- Custom CSS - checkbox-->
        <link href="BootStrap/css/checkbox.css" rel="stylesheet">

        <!-- Custom CSS - options-->
        <link href="BootStrap/css/bootstrap-multiselect.css" rel="stylesheet">

        <!-- Custom Fonts -->
        <link href="BootStrap/font-awesome/css/font-awesome.min.css"
              rel="stylesheet" type="text/css">

        <!--  Custom JavaScript -->
        <link href="BootStrap/Checkbox.js" rel="stylesheet"
              type="text/javascript">

        <!--  Custom JavaScript -->
        <link href="BootStrap/bootstrap-multiselect.js" rel="stylesheet"
              type="text/javascript">

        <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
        <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
        <!--[if lt IE 9]>
                <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
                <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
            <![endif]-->
<script language="javascript">
            function checkForm() {
                // declare an empty Object variable.
                var objForm = new Object();
                var objFullNameTextBox = new Object();
                var objMessageBox = new Object();
                var objAddress = new Object();

objForm = document.getElementById("frmData");
                objFullNameTextBox = document.getElementById("txtFullName");
                objMessageBox = document.getElementById("divMessage");
                objAddress = document.getElementById("txtAddress");

                strName = objFullNameTextBox.value;
                strAddress = objAddress.value;
if (strName == "") {
                    strMessageToUser += "Please indicate Name<br>";
                    blnIsAllOkay = false;
                }

 if (blnIsAllOkay == true) {
                    objForm.submit();
                } else {
                    objMessageBox.innerHTML = strMessageToUser;
                }

                function trimData(pstrData) {
                    var intIndex = 0;
                    var intRightIndex = pstrData.length - 1;
                    while ((intIndex < pstrData.length) && (pstrData.charAt(intIndex) == ' '))
                    {
                        intIndex++;
                    }
                    while ((intRightIndex > intIndex) && (pstrData.charAt(intRightIndex) == ' '))
                    {
                        intRightIndex -= 1;
                    }
                    return pstrData.substring(intIndex, intRightIndex + 1);
                }
            }
            function clearErr() {
                objMessageBox = document.getElementById("divMessage");
                objMessageBox.innerHTML = "";
            }
        </script>

And then in my html5 bootstrap template I have:

<div class="control-group form-group">
                            <div class="controls">
                                <label>Full Name:</label> <input type="text" class="form-control"
                                                                 id="txtFullName" name="txtFullName" required name="name"
                                                                 data-validation-required-message="Please enter your name.">
<div id="success"></div>
                        <!-- For success/fail messages -->
                        <button type="submit" id="btnSubmit" name="btnSubmit" onclick="checkForm" class="btn btn-primary">Submit</button>
                    </form>

However, when I left the name textbox blank, it doesn’t give out the error message: Please enter your name when I hit the submit button.

Hope someone can tell me what is wrong. Cos I am not sure if I can combine the old javascript on the new html5 bootstrap layout.

Without the javascript code, i can’t help you.

[off-topic]
@tangara when you post code in the forum, you need to format it. To do so you can either select all the code and click the </> button, or type 3 backticks ``` on a separate line both before and after the code block.

I have done it for you this time.
[/off-topic]

1 Like

First :

I don’t see an element with this id in your html.

Second :

useless.

Finally :
I dont understand how this script can work.
For example :
if you don’t enter in the if

The variable “blnIsAllOkay” doesnt exist.
And watch course on scope of variables.

You have to actually call checkForm() here, or better yet avoid inline JS altogether and use addEventListener() instead:

document
  .getElementById('my-form')
  .addEventListener('submit', checkForm)

And inside checkForm() you might also want to call event.preventDefault() or it will always get submitted.

Hello m3g4p0p,

First of all, thanks for pointing out the errors I have made. Really appreciate your help!

I am not quite clear what you meant by calling event.preventDefault() inside checkForm().

From W3School, I got this:

“document.getElementById(“myCheckbox”).addEventListener(“click”, function(event){
event.preventDefault()
});”

so, my checkForm is the function(event), do I add at
“function checkForm() {
event.preventDefault()
…
}”
and in this variable, I just add like that:

“objForm = document.getElementById(“frmData”).addEventListener(‘submit’, checkForm);”

Also, is this way of doing things outdated? cos this javascript way was done about 9 years ago and I heard there is react etc?

Will react be a better option?

Can I also know if the above will be able to function in all browser?

or

You still need to specify the event parameter though.

You don’t need to assign the return value of addEventListener() to a variable (which will be undefined anyway). What you can do is to assign the form reference as returned from getElementById() to a variable, especially if you want to reuse it elsewhere…

var myForm = document.getElementById('my-form')
myForm.addEventListener('submit', checkForm)

Other than the aforementioned inline JS it looks fine to me – you’re not using any deprecated APIs if this is your concern. On a general note though, I’d avoid the object constructor, just use an object literal instead (but as @YiuJia already mentioned, this object initialisation is not necessary here anyway). Another thing to avoid is the “loose equality” check as this can have quite unexpected results, always use the strict equality check instead (see here for details).

React would be quite an overkill for a simple form validation… what benefits do you think it would give you here? For a more modern approach you might have a look at HTML5 form validation though; for example, you can check if the validation constraints such as required are met directly like so:

myForm.addEventListener('submit', function checkForm (event) {
  event.preventDefault()

  if (myForm.checkValidity()) {
    myForm.submit()
  } else {
    // Show custom error message
  }
})

If you’re not sure if a certain feature is supported in all browsers you’re targeting, you can look it up on caniuse.com.

Hello m3g4p0p,

My javascript is really rusty after I focus on something else. I’d like to check if you are saying I could combine the HTML5 form validation with the javascript function ?

I am using a bootstrap template created by someone else but the required doesn’t work at all; as in when I left the fields blank it doesn’t show the error message.

<div class="control-group form-group">
                            <div class="controls">
                                <label>Full Name:</label> <input type="text" class="form-control"
                                                                 id="txtFullName" name="txtFullName" required name="name"
                                                                 data-validation-required-message="Please enter your name.">
                                <p class="help-block"></p>
                            </div>
                        </div>type or paste code here

May I know where do you define checkValidity() in the myForm.addEventListener function above?

The custom error message would be referring to the required-message ? So, I’d have to have one standard custom message otherwise I would have to repeat the above javascript for different kinds of field?

I wish there is an easy like a ready library out there that I can use for all the blank fields…is there one out there?

I have another problem - that the ide is aking me to use === instead of ==. How should the syntax be ?

   if (strName == "") {
                    strMessageToUser += "Please indicate Name<br>";
                    blnIsAllOkay = false;
                }type or paste code here

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.