Personalized verification script using bootstrap

I'm struggling with implementing form validation in my bootstrap form. I specifically want to use a regex pattern that only allows alphabets in the name field. However, my validation doesn't seem to be working. Can anyone help me identify the issue?

const nameinp = document.getElementById('nameinp');
let isPasswordValid = false;
let en = nameinp.value;
const ptern = /^[A-Za-z]+$/;
isPasswordValid = ptern.test(en);
(() => {
  'use strict'
  const forms = document.querySelectorAll('.needs-validation');

  Array.from(forms).forEach(form => {
    form.addEventListener('submit', event => {

      if (!form.checkValidity() || !isPasswordValid) {
        event.preventDefault()
        event.stopPropagation()
      }

      form.classList.add('was-validated')
    }, false)
  })
})()
<form id="Oform" action="" class="form-control needs-validation" novalidate>
  <label for=" OName">name</label>
  <input required id="nameinp" type="text" name="nameinp" id="OName" class="form-control">
  <div class="input-group form-control">
    <label class="col-sm-12" for="IPrange"> family</label>

    <input required class="form-control" type="text" name="" id="IPrange">
  </div>
  <button class="btn btn-success" id="submitbtn" type="submit">submit </button>
</form>

Answer №1

It is important to ensure that validation is triggered within the submit event for accurate results.

Currently, the validation only occurs when the form is loaded, not when it is filled and submitted.

Avoid using Array from unnecessarily.

It's worth noting that your test was only checking for the existence of a single character from a-zA-Z.

(() => {
  'use strict'
  document.querySelectorAll('.needs-validation')
  .forEach(form => {
    form.addEventListener('submit', event => {
      const nameinp = document.getElementById('nameinp');
      let isPasswordValid = false;
      let en = nameinp.value.trim();
      const ptern = /^[A-Za-z]*$/;
      isPasswordValid = ptern.test(en);
      console.log( isPasswordValid)
      if (!form.checkValidity() || !isPasswordValid) {
        event.preventDefault()
        event.stopPropagation()
        console.log('not valid')
      }
      // else // I would expect an else here 
      form.classList.add('was-validated')
    }, false)
  })
})()
<form id="Oform" action="" class="form-control needs-validation" novalidate>
  <label for=" OName">name</label>
  <input required id="nameinp" type="text" name="nameinp" id="OName" class="form-control">
  <div class="input-group form-control">
    <label class="col-sm-12" for="IPrange"> family</label>

    <input required class="form-control" type="number" max="254" min="1" name="" id="IPrange">
  </div>
  <button class="btn btn-success" id="submitbtn" type="submit">submit </button>
</form>

And if there is only one form then even less reason

(() => {
  'use strict'
  document.querySelector('.needs-validation')
    .addEventListener('submit', event => {
      const form = event.target;
      form.classList.remove('was-validated')
      form.classList.remove('invalid')
      const nameinp = document.getElementById('nameinp');
      let isPasswordValid = false;
      let en = nameinp.value.trim();
      const ptern = /^[A-Za-z]*$/;
      isPasswordValid = ptern.test(en);
      if (!form.checkValidity() || !isPasswordValid) {
        event.preventDefault()
        event.stopPropagation()
        form.classList.add('invalid')
      }
      else {
        form.classList.add('was-validated')
      }
    })
})()
.invalid { border: 1px solid red; }
.was-validated { border: 1px solid green; }
<form id="Oform" action="" class="form-control needs-validation" novalidate>
  <label for=" OName">name</label>
  <input required id="nameinp" type="text" name="nameinp" id="OName" class="form-control">
  <div class="input-group form-control">
    <label class="col-sm-12" for="IPrange"> family</label>

    <input required class="form-control" type="number" max="254" min="1" name="" id="IPrange">
  </div>
  <button class="btn btn-success" id="submitbtn" type="submit">submit </button>
</form>

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

When it comes to AFrame+Three.js, which is more efficient: having numerous meshes with minimal triangles per mesh or having a few meshes with a high number of

Currently working with Aframe 1.0.4 and Three.js 111, I am exploring the performance differences between: Whether it is better to have a few entities with a high number of triangles or many entities with fewer triangles each. Specifically, I am debating ...

Is it possible to swap a <div> element with the content of another HTML page using the .innerHTML method?

I am currently working on a project that involves loading different webpages into a <div> on my page once specific links are clicked. I came across a thread about using jQuery for this purpose, but I'm not familiar with it. Is there a way to ach ...

Choosing the following choice using the Material-UI Select tool

Looking for a way to enhance my dropdown select from MUI in a Nextjs application by adding two arrows for navigating to the next/previous option. Here's what my code currently looks like: <StyledFormControl> <Select value={cu ...

In order to enable automatic playback of background images

Having created a slider with hover functionality on icons to change background images, I now seek to add an autoplay feature to the slider. The slider was implemented in a WordPress project using Elementor and involved custom Slider creation through JavaSc ...

Having trouble displaying a modal using react hooks in bootstrap 5

I am encountering a console error when utilizing this component. ParseExceptionsModal.jsx:18 Uncaught TypeError: Cannot read property 'show' of null Here is the content of ParseExceptionsModal.jsx: import { Modal } from 'bootstrap'; i ...

What is the best way to manage user sessions for the Logout button in Next.js, ensuring it is rendered correctly within the Navbar components?

I have successfully implemented these AuthButtons on both the server and client sides: Client 'use client'; import { Session, createClientComponentClient } from '@supabase/auth-helpers-nextjs'; import Link from 'next/link'; ...

Response is sent by Sequelize Foreach loop before data is updated

My goal is to retrieve all content and media from a post, then append it to a new post before sending it as a response for easier access to the data. The issue I'm encountering is that the response is being sent before the content and media are fetche ...

How can the parameters -i -u "clientId:" be interpreted when translating a curl command into Ajax?

As I work on integrating a 3rd party API into my website, I am currently in the testing phase using Postman (the Chrome Extension) before proceeding to write my AngularJS Service with $http. However, there is one aspect of the process that has me puzzled. ...

What is the threading model utilized by node.js?

Upon establishing a connection with a server operating on node.js, how is the connection handled? Is it one connection per process? Does it follow a connection per thread model? Or does it operate based on request per thread? Alternatively, does it use ...

Tips for automatically resizing a canvas to fit the content within a scrollable container?

I have integrated PDF JS into my Vue3 project to overlay a <canvas id="draw_canvas"> on the rendered pdf document. This allows me to draw rectangles programmatically over the pdf, serving as markers for specific areas. The rendering proces ...

Error message: Electron is unable to read properties of undefined, specifically the property 'receive'. Furthermore, the IPC is unable to receive arguments that were sent through an HTML iframe

I am currently working on passing light mode and language data from ipcMain to ipcRenderer via my preload script: Preload.js: const { contextBridge, ipcRenderer } = require("electron"); const ipc = { render: { send: ["mainMenuUpdate& ...

Seamlessly transition between various states within a React component for a fluid user experience

I'm currently working on a simple component structured like this: var component = React.createClass({ render: function(){ if (this.props.isCollapsed){ return this.renderCollapsed(); } return this.renderActive() }, ren ...

Assign the physics settings to a variable within the A-frame

Exploring A-frame () for my scene creation has been exciting. I am curious about how I can dynamically adjust the physics in my virtual world using the A-frame physics component. The goal is to have the physics within my scene be determined by a variable c ...

Slideshow of table rows in HTML

On a webpage, I am populating an HTML table with a random number of rows ranging from 1 to 100. Regardless of the total number of rows, the requirement is to display only 10 rows at a time on the screen and then shift to the next set of 10 rows every 5 sec ...

What's the best way to pair a number with a neighboring letter?

const userInput = "2a smith road"; const secondInput = "333 flathead lake road, apartment 3b" const formattedAddress = userInput.replace(/(^\w{1})|(\s+\w{1})/g, letter => letter.toUpperCase()); The final result will ...

Obtaining data with jQuery.Ajax technology

I am attempting to retrieve real-time data from a different URL and display it in a text field every second without refreshing the entire page. The content of the URL is constantly changing, so I want the field to update accordingly. However, despite my ef ...

Implementing conditional dropdown menus with CodeIgniter

Explore the District Master Table: https://i.sstatic.net/n6kvV.jpg Dive into the District table: https://i.sstatic.net/uQqcW.jpg District Master District I need assistance with a form page that includes a Category dropdown. The district table stores d ...

What's the deal with dynamic prop values in React?

In my React application, I am trying to set a dynamic prop value. My goal is to use the first item in an array called Fruits and concatenate it with 'prop' to create the prop value. For example: ApplesProp index.js const ApplesProp = { Name: "G ...

Modifying CSS style according to the contents of an HTML element

Creating a room allocation page with multiple panel boxes using Bootstrap. Each box represents a bed - highlighted in red if occupied and green if vacant. Clicking on a green panel redirects to the room allocation page, while clicking on a red panel goes t ...

Encountered an issue while attempting to include multiple JavaScript sources. Please review your configuration settings for the javascripts.join

While setting up a basic app using phoenix-elixir and brunch, encountering the following error: 23 Mar 10:18:10 - warn: node_modules/phoenix/priv/static/phoenix.js compiled, but not written. Check your javascripts.joinTo config 23 Mar 10:18:10 - war ...