Validate with regex that the string contains only numbers and a negative sign at the beginning

Hello, I am attempting to create a regular expression for an input field that will only accept 4 numbers less than or equal to 2934, but will also allow for a negative number like -2394.

My goal is to permit the minus sign only at the beginning of the string, followed by exactly 4 numbers, not exceeding 2934 (both positive and negative, as they represent coordinates).

I have already tried the solutions provided here, but it seems like there is something missing.

function numonly(myfield, e, dec){
      // maximum input value of 4196 x 4196
      $("#mlat,#mlon").keyup(function() {
        var val = $(this).val().replace(/[^0-9]+/,"");
        if (val >= 2934){
          !/^\s*$/.test(val);
          val = (parseInt(val) > 2934) ? 2934 : val;
        }
        else {
          (!/^\s*$/.test(val));
          val = (parseInt(val) > 2934) ? 2934 : val;
        }
        $(this).val(val);
      });

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="mlat" type="text" name="mlat" maxlength="4" onkeypress="return numonly(this,event)"><br>
<input type="text" name="mlon" id="mlon" maxlength="4"  onkeypress="return numonly(this,event)">

Answer №1

I need to create a regular expression for an input field that only allows four numbers, not exceeding 2934, but also accepts negative numbers like -2394.

Instead of using regex, you can do the following:

var minValue = -2394;
var maxValue = 2934;    
var val = +$(this).val().replace(/[^0-9-]+/g,""); //using a custom regex to remove non-numeric characters
var isValid = !isNaN( val ) && val < maxValue && val > minValue ;

It seems like you want to set these values as the upper and lower bounds:

if ( !isNaN( val ) )
{
    var finalVal  = isValid ? val : (val < 0 ? minValue  : maxValue);
}

Answer №2

Here is a method you can use:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>
<input id="mlat" type="text" name="mlat" maxlength="5" onkeypress="return numonly(this,event)"><br>
<input type="text" name="mlon" id="mlon" maxlength="5"  onkeypress="return numonly(this,event)">
<script type="text/javascript">

function numonly(myfield, e, dec){

  // max input value of 4196 x 4196
  $("#mlat").keyup(function() {
    var val = $(this).val().replace(/-?\d+[^0-9]+/,"");
    if (val => 2934){
      !/^\s*$/.test(val);
      if (val > 0) {
        val = (parseInt(val) > 2934) ? 2934 : val;
      }else{
        val = (parseInt(val) > -2394) ? val : -2394;
      }

    }
    else {
      (!/^\s*$/.test(val));
      if (val > 0) {
        val = (parseInt(val) > 2934) ? 2934 : val;
      }else{
        val = (parseInt(val) > -2394) ? val : -2394;
      }
    }
    $(this).val(val);
  })
};


</script>
</body>
</html>

To accommodate the - sign in the input tag, remember to replace the maxlength with 5.

Answer №3

function limitNumbers(myfield, e, dec){
  // the maximum input value allowed is 4196 x 4196
  $("#mlat,#mlon").keyup(function() {
    var val = $(this).val().replace(/[^0-9-]+,"");
    if (parseInt(val) > 2934){
      val = (parseInt(val) > 2934) ? 2934 : val;
    }
    else {
      val = (parseInt(val) < -2934) ? -2934 : val;
    }
    $(this).val(val);
  });
}

Extend the max length to 5 to accommodate the use of '-'

<input id="mlat" type="text" name="mlat" maxlength="5" onkeypress="return numonly(this,event)"><br>
<input type="text" name="mlon" id="mlon" maxlength="5"  onkeypress="return numonly(this,event)">

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

Tips for implementing dynamic typing with Prisma

Encountering the error "this expression is not callable" while using the findUnique method with dynamic models. How can this type error be resolved? export const isFound = async ( model: Prisma.ModelName, id: string | number, idName: string ): Promis ...

What is the best method for verifying a specific condition in every element of a 2D array?

:) I'm in the process of developing a maze using JS and P5, which involves utilizing a two-dimensional array filled with numbers 0-8. Specifically, 0 represents empty spaces, 1 denotes walls, 2 signifies the character you control, 3 marks the exit poi ...

Guide on converting data from PHP to JSON using JavaScript

Here is some data that I need to loop through: image1 url1 description1 image2 url2 description2 image3 url3 description3 image4 url4 description4 image5 url5 description5 After looping through the data: var imagesDataArray = [ { src: &apo ...

How can I handle the issue of the body background overlapping with the modal window?

Recently, I created a dialog box using the code below: $(function(){ $('#saveandcontinue').click(function(){ $('body').css('background', '#999'); $('.footer').css('background&a ...

What is the best way for a function to pause until the variable 'rows' holds the outcome of a mysql query?

The client.mysqllocal function should be returning rows. Here's the code I'm currently using: https://pastebin.com/hgt2DwSY const mysql = require('mysql2'); let pool = mysql.createPool({ connectionLimit : 10, hos ...

The longevity of JQuery features

As I work on setting up an on-click callback for an HTML element to make another node visible, I encountered a surprising realization. The following two statements appeared to be equivalent at first glance: $("#title").click($("#content").toggle); $("#tit ...

Using the includes method with a switch statement in Javascript

Hey there, I'm facing a bit of a challenge here. It seems like what I'm attempting to do might be more complex than I initially thought or my brain is just not cooperating. I'm currently working on using a switch statement to verify if a str ...

I am trying to access a value saved in a service in Angular 8 component and use it in other services. Can anyone help

Setting a value through a component export class UniqueComponent { constructor(service:UniqueService){ } count =0 ; onRefresh(){ this.service.count = 1; } } Using the value in the service UniqueService{ count:any; doSomething(){ //using count ...

Transforming a string to a Date object using JavaScript

Can someone assist me in converting a PHP timestamp into a JavaScript Date() object? This is the PHP code I use to get the timestamp: $timestart = time(); I need help converting this timestamp into a JavaScript date object. The concept of working with d ...

Using jQuery ajax in PHP, the ability to remove retrieved information from a different page is a

I'm currently working on a jQuery AJAX PHP application that allows for adding, deleting, and displaying records using switch case statements to streamline the code. Everything seems to be functioning correctly with inserting and displaying records, bu ...

What is the best method to delete an element from an array that contains specific characters?

I am looking to filter out specific values from an array. var array = [<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2149444d4d4e615840494e4e0f424e4c">[email protected]</a>, www.hello.com, <a href="/cdn-cgi/l ...

extracting and saving the link value from a JSON file

Developing an app using PhoneGap for Android and extracting content from a local JSON file. Everything is functioning correctly without the addition of links. However, when I try to include a link value, it stops working. The following code is appearing ...

Transforming jQuery into classic JavaScript traditions

I want to convert the code below into pure JavaScript. document.addEventListener('click', function(event) { if (event.target.classList.contains('savedPlayer')) { event.preventDefault(); let searchText = event.target.textCon ...

Different methods for looping through undefined values within Arrays

While exploring the use of .map, I made an interesting discovery regarding arrays with holes, where certain indices are defined while others remain undefined: // Holed var array = []; array[0] = 1; array[2] = 3; array // => [1, undefined, 3]; // Not H ...

Displaying NodeJS error messages directly in the main HTML file

After creating a form using NodeJs and implementing input validations that display errors when users enter incorrect values, I encountered an issue where the errors appear on a new blank page instead of within the main HTML file itself with stylish formatt ...

What options do I have for personalizing event listeners in d3.js?

I am currently working on a simple program that involves using a slider to move a rectangle across a webpage. I have set up the slider like this: <input type = "range" min = "5" max = "500" value = "5" id = "xvalue" > and I am able to access the sl ...

Displaying Angular JS 1.5 component's HTML content in the browser as a commented-out section

Exploring the Angular world and facing a challenging issue with a basic angular component. My goal is to incorporate a custom element called "cast-tile" on the page, loaded by angular as a component. However, the browser seems to be treating the code in n ...

Using JQuery Datepicker with an icon and custom format in ASP.NET

I am looking to incorporate jQuery into my Textbox. Specifically, I would like to use the Datepicker with the format yyyy-mm-dd and include an Icon as well. <script> $( "#txtVon" ).datepicker({ showOn: "button", buttonImage: "ima ...

Utilizing regex patterns within Jqgrid

I am currently utilizing the JqGrid plugin (version 4.6.0 - jQuery Grid) to filter my results using specific fields. Here is an example of how the GUI appears: https://i.sstatic.net/BqGai.png With a large list of employees, I want the ability to filter t ...

Running a function in Vue.js after another function, synchronously

I want to ensure that one function runs after another in VueJs data: function() { return { stuff: '', myArray:[ { "id": 0, "value1": 0, ...