Variable should contain only two words, with the option to include a dash

I am looking for a way to limit users from inputting more than two words, but still allow words with a dash in them.

Allowed

Mike-David Smith

Not Allowed

Mike David Smith

The code I have only restricts input to two words and does not consider words with dashes as single words. Here is the current code:

<script type="text/javascript">//<![CDATA[
$(function(){
var maxWords = 2;
jQuery('#fullname').keypress(function() {
var $this, wordcount;
$this = $(this);
wordcount = $this.val().split(/\b[\s,\.-:;]*/).length;
if (wordcount > maxWords) {
    alert("Please enter a maximum of 2 words (forename and surname)");
    return false;
} 
});

jQuery('#fullname').change(function() {
var words = $(this).val().split(/\b[\s,\.-:;]*/);
if (words.length > maxWords) {

    words.splice(maxWords);
    $(this).val('');
   ////////// alert("Please enter a maximum of 2 words (forename and surname)");
}
});
});//]]> 

</script>

Your help is greatly appreciated. Thank you!

Answer №1

Here are some modifications to make in your regex pattern:

  • You don't need to specify a word boundary \b since you are splitting, not matching.
  • Remove the hyphen - from the character set.
  • Use + instead of * to allow consecutive occurrences of colons, spaces, etc as one separator.

For example:

"Mike-David Smith".split(/[\s,\.:;]+/) //["Mike-David", "Smith"]

Check out the demo below:

var regex  = /[\s,\.:;]+/;

console.log("Mike-David Smith".split(regex));
console.log("Mike David Smith".split(regex));
console.log("Mike-David-Smith".split(regex));

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

Organize angularjs ngRepeat with updated data outcomes

I am facing a situation where I need to display results from different ajax sources, but they are loaded asynchronously. The problem is that I want the results to be sorted alphabetically once they are all loaded. ngRepeat doesn't sort them correctly ...

.Certain IDs on a website may not respond to clicks due to various reasons

I have created a JavaScript file to automatically click a button on a website using a Chrome extension. When testing the code using Chrome Script snippet, I noticed that it worked for some IDs but not for others. Can someone please help me with this issue? ...

Is it possible to execute ng-repeat on-click when ng-show evaluates to true?

I am currently facing an issue with my table that populates using ng-repeat. The table contains 100 rows, and clicking on any row reveals a new table (using ng-show) with more detailed product information. However, the performance of my web app is being af ...

Explore the data within a directory containing files and subfolders using javascript, HTML5, AngularJS, or jQuery

I'm looking to access and read files as well as subfolders within a folder that is selected using <input type="file"> I understand that I could potentially use <input type="file" multiple webkitdirectory />, but this solution is specific ...

What is the process for saving information to a database with JavaScript?

I am currently utilizing the Google Maps API for address translation, primarily through the use of a geocoder. I am interested in saving these results to a local database for future reference, as there are limitations on the total number and frequency of ...

Guide to moving a 3D model and initiating animation in threejs when a key is pressed

In the midst of a project where a person (gltf object) walks based on key presses, I have successfully updated the object position accordingly. However, I'm encountering difficulty in rotating the object when the left/right keys are pressed and ensur ...

Is it possible for me to use the name "Date" for my component and still be able to access the built-in "new Date()" functionality?

Currently following the NextJS tutorial, but adding my own twist. In the NextJS example, the custom component is named "Date" (/components/date.js) and does not utilize the built-in Date() object in processing, making it unique to the file. In my scenario ...

While executing a jssor code in SP 2007, IE experiences freezing issues

I've integrated a jssor slider with vertical navigation (without jQuery) into a Sharepoint 2007 page using CEWP. All the image links have been replaced with images stored in the SP image library, and the jssor.slider.min.js file has been uploaded to t ...

Leveraging Javascript to retrieve PHP variables

I'm trying to figure out how to get access to PHP variables from Javascript when the PHP code is in a separate file. Here's the code I currently have: <?php $res = "OK"; ?> <html> <head> <script type="text/javascript"&g ...

Identifying Inactivity in Cordova Android Applications

Hey there! So, I've created a flashlight/torch app that can be found at the following link: https://github.com/Skelware/Fancy-Flashlight. This app utilizes a Cordova plugin available here: https://github.com/Skelware/Cordova-Flashlight. For now, my m ...

Invoking a static method within a cshtml document

I am currently working on implementing a clickable DIV within a vertical tab panel. My goal is to have a specific static method called when the DIV is clicked. Here is what I have done: <div class="tabbable tabs-left"> <ul class="nav nav-tabs"> ...

What is the best way to adjust the size of a 3D Cube in WebGL GLSL without affecting its center point?

I have a scaling attribute that I am applying to various instances of an instanced buffered geometry in Three.js. The shader code appears as follows: attribute float scale; uniform vec3 uMeshPosition; void main() { vec3 pos = position; pos.x *= (uMe ...

What is the best way to interrupt the current song playing?

I am currently working on developing an audio player using reactjs that has a design similar to this https://i.sstatic.net/Hnw0C.png. The song boxes are rendered within a map function, and when any song box is clicked, it should start playing. However, I a ...

Is it necessary for me to authenticate jwt tokens?

Let me explain my situation. I have generated a JWT token and stored it in Redis with a TTL of 1 hour. Now, most tutorials suggest using jwt.verify to authenticate the token. I understand that jwt.verify is used to verify whether the token is authentic or ...

Tips for preserving my cookies and URLs in a text file

I'm facing an issue with logging my Cookies and URL. I am able to log them, but I am struggling to set them to variables. Can someone please assist me with this? When I try to set both of them to variables, all I get in return is Promise { } driver ...

Unable to interpret data from JSON file

I have written the following code to read a JSON file. It is not throwing any errors, but I am receiving a null value in the variable: var myData = null; $.ajax({ type: 'GET', async: false, url: 'myJson.json', dataType: ...

Looking for assistance with embedding content into an iFrame?

Having trouble writing into an iframe, I can locate the iframe but unable to input anything into it. Every time I attempt to write into the iframe, I encounter the following error. <div id="offer_description_field" class="control-group wysihtml5_type d ...

Dynamic data retrieval with the power of JavaScript and AJAX

When attempting to send data using AJAX in PHP, I encountered an issue with my jQuery click function on a button that sends data only when the quantity is greater than 1. The error arises because PHP does not recognize the variables 'name' and &a ...

Once the page is refreshed, the checkbox should remain in its current state and

I have a challenge with disabling all checkboxes on my page using Angular-Js and JQuery. After clicking on a checkbox, I want to disable all checkboxes but preserve their state after reloading the page. Here is an example of the code snippet: $('# ...

Experiencing slow loading times with a Next.js app in the development environment

Currently, I am in the process of building a Next.js application and I have noticed that it takes quite a long time to load in the development environment. At the start, the page becomes unresponsive and if I cancel the request, it stops loading altogeth ...