1

My code

<body>
    <div>
        <form onsubmit="displaySum(); return false">
        <h1>Sum of two numbers</h1>
        <br>
        <input id="number1" class="read" type="text" pattern="^[-\d]\d*$" required placeholder="Enter number 1">
        <input id="number2" class="read" type="text" pattern="^[-\d]\d*$" required placeholder="Enter number 2">
        <button id="submit-button" type="submit">Add</button>
        <h1 id="displayArea"></h1>
        </form>
    </div>
    <script>
        function displaySum()
        {
           
            let num1=parseInt( document.getElementById("number1").value );
            let num2=parseInt( document.getElementById("number2").value );
            let sum = num1 + num2;
            console.log("Sum is: "+ sum);
            document.getElementById("displayArea").innerHTML=sum;
        }
    </script>
</body>

My output

I got this error message:

Pattern attribute value ^[-\d]\d*$ is valid with the RegExp u flag, but not with the v flag: Uncaught SyntaxError: Invalid regular expression: /^[-\d]\d*$/v: Invalid character in character class. See https://crbug.com/1412729

I wanted to read two integers and output its sum on the screen and console. I tried matching pattern to read integer values and I got the output right. But I'm stuck with the error message.

  • Inputs, outputs and error messages should be given as text. Images may only be used to provide extra details. Please take the [tour] and read the [help] pages to learn how to write a question that matches the rules of this site. – AdrianHHH May 14 '23 at 08:44
  • 1
    To add details please [edit] the question. Adding unformatted text in comments is not helpful. – AdrianHHH May 14 '23 at 08:50
  • RegExp ES6 has `g`, `i`, `m`, `s`, `u`, and `y` flags, I don't recall any `v` flag. In fact `v` flag doesn't exist in PCRE, Python, Java, etc. either. – zer00ne May 14 '23 at 08:57
  • I haven't used any flag. But I wonder why it shows this error message. – Nafeesath Musfira Badriya May 14 '23 at 09:07
  • Also, the hyphen `-` needs to be escaped like so: `[\-\d]`. Having the unescaped hyphen inside a character class requires that it be surrounded by numbers, lower case letters, or upper case letters -- it serves as a range of numbers or letters. ex. `[0-9]` or `[a-z]` . Also, the `^` and `$` indicate the beginning and ending of a line, but it will be syntactically incorrect if the `m`ulti-line flag isn't used. Also, the additional `\d*` seems unnecessary. In short wouldn't `/^-?\d+$/m` work? It'll accept zero to one `-` then one or more numbers. – zer00ne May 14 '23 at 09:17
  • @zer00ne In many RegEx implementations a hyphen as the first or last item in a character character class means itself. Thus `[-\d]` and `[\d-]` both mean digits or hyphen. – AdrianHHH May 14 '23 at 09:20
  • @AdrianHHH in a character class the "^", "-", "]", and "\" characters are actual tokens. That's why the error message: *"Invalid character in character class"* appears. – zer00ne May 14 '23 at 10:24
  • @NafeesathMusfiraBadriya see my [answer](https://stackoverflow.com/a/76247009/2813224) for a complete solution. – zer00ne May 14 '23 at 10:39
  • @zer00ne Please see the item starting *"To use a literal `-` in a character class ..."* within https://npp-user-manual.org/docs/searching/#character-classes. All other RegEx versions I have used have the same interpretation. Note that a hyphen *between* characters denotes a range of characters, but a leading or trailing hyphen only has a value on one side, so cannot denote a range. – AdrianHHH May 14 '23 at 16:27
  • @AdrianHHH Ok, I see what you're saying, thanks for pointing that out. I never place a literal hyphen in a class set because the placement of a hyphen needs to be specific in most cases. ex. an integer will either have a single hyphen prefixed to a whole number or it doesn't have one at all -- a class character hyphen could be found between numbers or suffixed to a number. – zer00ne May 14 '23 at 16:56
  • See also: [Valid with the RegExp `u` flag, but not with the `v` flag](https://stackoverflow.com/q/76285652). `` `pattern`s are now compiled with the `v` flag, which requires leading and trailing hyphens in character classes be escaped. – InSync Jun 29 '23 at 16:22

1 Answers1

0

A simpler RegExp for [pattern] that accepts negative and positive integers is as follows:

<!-- [title] is included in error message -->
<input pattern="-\d+|\d+" title="Must be a negative or positive integer">

RegeExp: -\d+|\d+

Segment Description
-\d+
match hyphen followed by one or more digits
|
OR
\d+
match one or more digits

Example

As an added bonus there's an "input" event handler that expands the width of an <input> when there are more than 5 characters entered by the user.

Details are commented in example

// Reference <form>
const F = document.forms.calc;
/*
Reference all form controls in <form>
In this case it would be all <input>, <button>, and <fieldset>
*/
const fc = F.elements;

/*
Register the <form> to the "submit" event -- call sum()
Register the <form> to the "input" event -- call extend()
*/
F.onsubmit = sum;
F.oninput = extend;

// Event handlers always pass the Event Object
function sum(event) {
  // Stop <form> from sending data to server
  event.preventDefault();
  // Get the values of both <input> and convert them into numbers.
  let n1 = parseInt(fc.number1.value);
  let n2 = parseInt(fc.number2.value);
  // Display the sum in fieldset#result
  fc.result.textContent = n1 + n2;
}

function extend(event) {
  // Reference the form control that the user is entering data into.
  const inp = event.target;
  /*
  If the fc that the user is entering data into has class ".read" 
  AND it is NOT <form>...
  ...qty is the current number of characters the inp has..
  ...If inp has more than 5 chars in it...
  ...the inp width is increased...
  ...otherwise it will be 5ch wide
  */
  if (inp.matches(".read") && inp != this) {
    let qty = inp.value.length;
    if (qty > 5) {
      inp.style.width = qty + "ch";
    } else {
      inp.style.width = "5ch";
    }
  }
}
:root {
  font: 2ch/1 Consolas
}

input,
button {
  display: inline-block;
  font: inherit;
}

input {
  text-align: right;
  width: 5ch;
}

#ui {
  position: relative;
  display: flex;
  align-items: center;
}

#ui>* {
  margin: 0 5px;
}

#result {
  display: inline-block;
  padding: 0;
  border: 0;
}

button {
  position: absolute;
  right: 3px;
  cursor: pointer;
}
<form id="calc">
  <fieldset id="ui">
    <legend>Sum of Two Integers</legend>
    <!--
      [pattern] is as follows:
      match a hyphen: "-" followed by one or more digits 
      OR
      match one or more digits.
      If the data doesn't match the [pattern] during the
      "submit" event, the text in [title] will be included
      with the error message.
    -->
    <input id="number1" class="read" type="text" pattern="-\d+|\d+" title="Must be a negative or positive integer" required> +
    <input id="number2" class="read" type="text" pattern="-\d+|\d+" title="Must be a negative or positive integer" required> =
    <fieldset id="result"></fieldset>
    <button>Add</button>
  </fieldset>
</form>
zer00ne
  • 41,936
  • 6
  • 41
  • 68