Requirements for adding information to a database table

I'm new to JavaScript and facing an issue that I need help with. I am trying to insert data into a database table based on certain conditions in my code, but even though I receive an error message when I input incorrect values, the data still gets inserted into the database. Can someone guide me on what should go inside my if statement to prevent this? Any assistance would be greatly appreciated! Here is my index.js

    var manageMemberTable;
    $("#addMemberModalBtn").on('click', function() {
        // reset the form 
        $("#createMemberForm")[0].reset();
        // remove the error 
        $(".form-group").removeClass('has-error').removeClass('has-success');
        $(".text-danger").remove();
        // empty the message div
        $(".messages").html("");

        // submit form
        $("#createMemberForm").unbind('submit').bind('submit', function() {

            $(".text-danger").remove();

            var form = $(this);

            // validation
            var firstname = $("#firstname").val();
            var lastname = $("#lastname").val();

This is the specific condition I am checking for

    if (firstname == "") {
                $("#firstname").closest('.form-group').addClass('has-error');
                $("#firstname").after('<p class="text-danger">The firstname field is required</p>');
            }
            else {

            if (firstname.match(/^[a-zA-Z ]+$/) === null){
                $("#firstname").closest('.form-group').addClass('has-error');
                $("#firstname").after('<p class="text-danger">Firstname invalid</p>');
            }
            else {
                $("#firstname").closest('.form-group').removeClass('has-error');
                $("#firstname").closest('.form-group').addClass('has-success');
            }   
            }           


                //lastname validation

                if (lastname == "") {
                    $("#lastname").closest('.form-group').addClass('has-error');
                    $("#lastname").after('<p class="text-danger">The lastname field is required</p>');
                }
                else {

                if (lastname.match(/^[a-zA-Z ]+$/) === null){
                    $("#lastname").closest('.form-group').addClass('has-error');
                    $("#lastname").after('<p class="text-danger">lastname is invalid</p>');
                }
                else {
                    $("#lastname").closest('.form-group').removeClass('has-error');
                    $("#lastname").closest('.form-group').addClass('has-success');
                }
                }

Here is where the conditional statement should go

if( // Need help defining this conditional check) {
                //submit the form to server
                $.ajax({
                    url : form.attr('action'),
                    type : form.attr('method'),
                    data : form.serialize(),
                    dataType : 'json',

Answer №1

Here is one possible solution.

firstname.match(/^[a-zA-Z ]+$/) will return true if the input string meets the specified regular expression criteria.


if ((firstname != "") && (firstname.match(/^[a-zA-Z ]+$/)) &&
    (lastname != "") && (lastname.match(/^[a-zA-Z ]+$/))) {
    $("#firstname").closest('.form-group').addClass('has-success');
    $("#lastname").closest('.form-group').addClass('has-success');    
    // Send data to database here
}
else {
    if(firstname === ""){
        $("#firstname").closest('.form-group').addClass('has-error');
        $("#firstname").after('<p class="text-danger">The firstname field is required</p>');
    }
    if (!firstname.match(/^[a-zA-Z ]+$/)){
        $("#firstname").closest('.form-group').addClass('has-error');
        $("#firstname").after('<p class="text-danger">Invalid firstname value</p>');
    }
    if(lastname === ""){
        $("#lastname").closest('.form-group').addClass('has-error');
        $("#lastname").after('<p class="text-danger">The lastname field is required</p>');
    }
    if (!lastname.match(/^[a-zA-Z ]+$/)){
        $("#lastname").closest('.form-group').addClass('has-error');
        $("#lastname").after('<p class="text-danger">Invalid lastname value</p>');
    }  
} 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trouble with ajax call in Internet Explorer 8

Seeking assistance with a straightforward ajax request triggered by a user altering a select element. Implemented using jquery .ajax, the current functionality (which works in all browsers except Internet Explorer) involves loading a .html file via ajax, ...

The jQuery function $.post fails to include information about which button was clicked in the request

I've encountered a problem where $.post isn't sending information about which button was pressed in my form. The scenario is having a form with two buttons: <form method="post" action="/home/index"> <input type='hidden' n ...

Having trouble retrieving PHP variable values using JavaScript?

<div id="div01">01</div> <div id="div02">02</div> <img src="../img/logo.png" onclick="blueSky()"/> js function blueSky() { $.ajax({ type:'GET', url: 'test.php', success: function(respond) { document.ge ...

Selecting default values from the Vuex store in Vue-Multiselect

Picture a Vuejs-Application equipped with Vuex. I am aiming to incorporate a mulitselect-dropdown. Here's a basic example inside the Vue-component: <template> <div> <multiselect v-model="values" :options="options"> ...

What is the method for modifying the chosen color using a select option tag instead of a list?

element, I have a Vue component that features images which change color upon clicking a list item associated with that color. <div class="product__machine-info__colors"> <ul> <li v-for="(color, index) in machine.content[0] ...

Analyzing and sorting two sets of data in JavaScript

I am currently working with two arrays that are used to configure buttons. The first array dictates the number of buttons and their order: buttonGroups: [ 0, 2 ] The second array consists of objects that provide information about each button: buttons = ...

Transferring data between functions within the same controller in AngularJS

I have implemented two functions to handle the timing of a process, one for starting and one for stopping. Here is the code snippet: $scope.start = function(data) { $scope.time = { id: '', mainId: data.id, start: &ap ...

Tips on deleting CSS comments from a CSS file

Currently, I am utilizing nextjs + reactjs. My objective is to eliminate all CSS comments from my existing css file. Despite using next-purgecss in order to get rid of unnecessary CSS code, the comments are still persisting. What could be the reason behind ...

Maximum limit reached for call stack size in the magnificpopup

I've encountered an issue with a stackoverflow error! After tracing back the source code to the setFocus and onFocusIn functions in the magnificpopup js file, I am still unable to pinpoint where the error is being generated. In the following code sn ...

Having multiple upload forms on a single page with PHP, AJAX, and jQuery is not functioning as expected

I'm on the hunt for a jQuery-AJAX image uploader that supports multiple instances of the form on a single page. Do you have any recommendations? Here's my scenario: I have a front-end page where users can update their profiles. Upon loading the ...

Tips for unit testing an Angular Service that is primarily responsible for redirecting to an external page from the application

My service is responsible for redirecting to a separate login page since we are implementing login as a service. function redirectToMembership() { var returnURL = $location.host(); returnURL+="/#/Authorization"; $window.location.href=Environme ...

What is the best way to retrieve user data and format the output using JavaScript into a structured form?

I am trying to achieve the functionality shown in this image: https://i.sstatic.net/svzvc.png My goal is to extract user input from a form and display it on my webpage using JavaScript. Below is the code snippet that I have been working on. Code: f ...

Is there a way to identify and count duplicate data-items within an array, and then showcase this information using a react view?

If we have an array like this: [{id: 1, name: "chocolate bar"}, {id:2, name: "Gummy worms"}, {id:3, name:"chocolate bar"}] Is there a way to show on the dom that we have "2 chocolate bars and 1 Gummy Worms"? ...

Transferring information among various instances of a single controller (ng-controller)

I am relatively new to using Angular and I am facing a challenge with a seemingly simple task that is proving to be more complex within the framework. The issue at hand involves data manipulation, specifically with a variable named var1. I am modifying th ...

What happens to PHP echos when you send a post request to a web page?

I have a question that may seem silly to some. As someone who is relatively new to PHP, I am attempting to view echo statements from a page that I am posting to but not actually navigating to. Directly accessing the page's URL without the necessary po ...

What is the best way to determine the file size using Node.js?

My current challenge involves using multer for uploading images and documents with a restriction on file size, specifically limiting uploads to files under 2MB. I have attempted to find the size of the file or document using the code below, but it is not p ...

Fully responsive header designed for optimal experience at any screen height

I am facing issues with the header and cannot seem to find a solution. My goal is to make the header span 100% of the window screen height. I need a responsive header that adjusts to 100% height, and when resizing for a smaller viewport, nothing should sho ...

What is the proper way to include enctype in my jQuery post request?

I've attempted to include it in my code, but it's not functioning properly. Even though all my form values are serialized and submitted through ajax, I can't seem to post my file name because it needs the enclosure type to be included. subm ...

Guide to delivering a PDF document from a controller

In my pursuit to send a PDF file from a Controller Endpoint using NestJs, I encountered an interesting issue. Without setting the Content-type header, the data returned by getDocumentFile function is successfully delivered to the user. However, when I do ...

How does the 'order' stack up against the 'products' array? Display the names of the products that are included in the order

I have an array of items for sale: const products = { { id: product1, name: 'Product A', price: 100 }, { id: product2, name: 'Product B', price: 200 }, { id: ...