Confirm the text field input to accept only alphabets, hyphens, and periods

I want to enhance the validation of my text field by restricting it to only allow letters a-z and -.

Currently, if the input is invalid, a cross appears, and if it's valid, a check mark appears. However, I need the validation to also check for minimum and maximum character limits, such as having a minimum of 5 and a maximum of 60 characters.

In addition, I am facing an issue where the validation allows the @ character in certain cases, like 'hello@', when it shouldn't be allowed on its own.

Here is my current script:

<script>
function validateCname(CnameField){
    var reg = /[A-Za-z\._-]$/;

    if (reg.test(CnameField.value) == false) 
    {
        document.getElementById("emailTick").style.display='none';
        document.getElementById("emailCross").style.display='block';
        return false;
    }
    if (reg.test(CnameField.value) == true) {
        document.getElementById("emailCross").style.display='none';
        document.getElementById("emailTick").style.display='block';
        return true;
    }
}
</script>

HTML:

<input type="text" id="field_cname" name="cname" class="field_cname" onfocus="document.getElementById('field_cname').style.background='#ffffff';" onblur="validateCname(this);">
<div id="emailCross"></div><div id="emailTick"></div>

Answer №1

Update your regular expression to:

let regEx = /^[A-Za-z\._-]{5,60}$/;

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

Creating a worldwide entity through the use of an Immediately Invoked Function Expression

There are 2 methods I discovered for defining a global object using IIFE: (function () { var func = function () { }; window.func = func; }()); compared to: (function (myFunc) { window.func = myFunc(); }(function () { var func = functi ...

The implemented JavaScript prompt feature is malfunctioning within the HTML environment

I have been tasked with creating a curriculum program that prompts students to input the number of hours they study each day. However, I am encountering issues with getting the prompt command to function within this JavaScript code: <html> <body& ...

Facing the issue of "Protractor not syncing with the page" while trying to navigate an Angular website

I'm currently attempting to follow the tutorial for Protractor on the official Protractor website, but I've hit a roadblock at step 0. My setup involves using protractor and webdriver-manager version 6.0.0. I am running Linux (Ubuntu 18.06) as m ...

"What is the best way to include additional fields within a popover in an AngularJS application

This is my code for implementing a popover using AngularJS. I am trying to figure out how to add custom styling to the popover HTML, but I am having trouble binding elements in that part of the code. <!DOCTYPE html> <html> <head> <l ...

The themes showcased in the Bespoke.js documentation and demo exhibit unique designs

Recently, I stumbled upon an incredible HTML5 framework for presentations. For more information, you can check out the documentation here. You can also view a demo of the framework by visiting this link. However, I was disappointed to find that the caro ...

Is there a way to prevent certain code from executing during server deployment?

First of all, my apologies for any mistakes in my English language skills. I find Morgan to be a great tool for development, but I am uncertain about deploying my server and not wanting everyone to see who is online. How can I prevent certain actions fro ...

Is it possible to use Google API to fetch specific sections of a document by referencing headings?

I have a document that I extract text from to insert into my webpage. This document is getting larger as it covers more areas, so I want to streamline the process for my single-page application. Currently, I retrieve the entire document using the code snip ...

What could be causing Jquery to not function properly in an Angular controller?

Can someone please help me understand why my code is not working in JSFiddle? Any assistance would be appreciated! UPDATE: I have to admit, the negative feedback is disheartening. I may not know everything, but asking questions is how we learn. What' ...

Error: The function does not exist for collections.Map

I'm encountering a TypeError on my page: collections.Map is not a function. Below is my JavaScript code and I can't seem to figure out what the issue is. this.state = { collections: SHOP_DATA }; render() { const {collections} = this.sta ...

Preventing Copy and Paste and Right-Click Actions With JavaScript

Similar Question: How can I prevent right-click on my webpage? Looking to prevent right-clicking and key combinations like Ctrl+V & Ctrl+C on a webpage using JavaScript. I have a form where customers need to input their details, and I want to avoid ...

Initiate a fresh start with an automatic input reset

When you perform an action in the first id = "benodigheden", I believe there should be a specific outcome that then triggers a second rule for id = "benodigheden". However, I have been unsuccessful in finding information on this topic online. It seems like ...

Odd behavior of dropdown list on Internet Explorer 8

Thank you for taking the time to review this. I have a dynamic dropdown list that changes its content based on a specific value (for example, "51") inputted into the JavaScript code on each page. Different pages display different lists depending on this va ...

What is the best way to move an element to a different position?

I'm currently practicing JavaScript and Dynamic HTML through a course I'm taking. While checking my code in Firefox and Chrome, I haven't come across any errors or warnings so far. However, there might be something I'm missing or doing ...

Discovering the meeting point where two dives converge

Is there a method to change the color of the overlapped common part of two animated circles? ...

The ViewChild instance is currently undefined

Within my component, I have the following setup: @ViewChild('PaginatedTableComponent') userTable: PaginatedTableComponent; Here is the corresponding HTML code inside the component: <pag-paginated-table #userTable [(shouldUpdate)]="sh ...

Rendering JSON data in a dropdown menu

When I select an option, all the data is being combined into one row. I want the data to fill each row based on the select option. Any suggestions on what code I should modify or add? Is it related to the loop or should I create a dynamic id for the selec ...

Issue with Backbone: Unable to access property 'fn' as it is undefined

When I attempt to run the code below, I encounter an error that says "Cannot read property 'fn' of undefined" due to jquery not being found. requirejs.config({ baseUrl: "/static/javascript", paths: { jquery: "vendor/jquery", undersco ...

Black textures with images sourced from the same domain - Cross-origin

Despite trying numerous solutions and tips to resolve the cross-origin issue, I still can't seem to fix it. There are no errors, the images are hosted on the same domain as the webgl test, but the textures appear black. Occasionally when I refresh rep ...

Troubleshooting Issue with Internet Explorer failing to update Asp.Net MVC3 Partial View

I am experiencing an issue with a page that includes a div for a partial view loaded via an ajax request. $.ajax({ url: 'CompleteSessions', success: function (data) { var selector = $('#complete-session-sect ...

The "loose" mode is not resolving the issue with the lack of support for the experimental syntax 'classProperties' that is currently disabled

Error Message: The experimental syntax 'classProperties' is currently not enabled Even after trying the suggested solutions, I still encounter the error during re-building. Click here for more information on the experimental syntax 'classP ...