Browse Source

x-mask $money allow for negative values (#3416)

* Allow negative values

* add test
Restartz 2 years ago
parent
commit
8f76b280ec
2 changed files with 20 additions and 1 deletions
  1. 3 1
      packages/mask/src/index.js
  2. 17 0
      tests/cypress/integration/plugins/mask.spec.js

+ 3 - 1
packages/mask/src/index.js

@@ -171,6 +171,7 @@ export function buildUp(template, input) {
 }
 
 export function formatMoney(input, delimiter = '.', thousands) {
+    if (input === '-') return '-'
     if (/^\D+$/.test(input)) return '9'
 
     thousands = thousands ?? (delimiter === "," ? "." : ",")
@@ -194,10 +195,11 @@ export function formatMoney(input, delimiter = '.', thousands) {
         return output
     }
 
+    let minus = input.startsWith('-') ? '-' : ''
     let strippedInput = input.replaceAll(new RegExp(`[^0-9\\${delimiter}]`, 'g'), '')
     let template = Array.from({ length: strippedInput.split(delimiter)[0].length }).fill('9').join('')
 
-    template = addThousands(template, thousands)
+    template = `${minus}${addThousands(template, thousands)}`
 
     if (input.includes(delimiter)) template += `${delimiter}99`
 

+ 17 - 0
tests/cypress/integration/plugins/mask.spec.js

@@ -191,3 +191,20 @@ test('$money mask should remove letters or non numeric characters',
         get('input').type('40').should(haveValue('40'))
     }
 )
+
+test('$money mask negative values',
+    [html`
+        <input id="1" x-data x-mask:dynamic="$money($input)" value="-1234.50" />
+        <input id="2" x-data x-mask:dynamic="$money($input)" />
+    `],
+    ({ get }) => {
+        get('#1').should(haveValue('-1,234.50'))
+        get('#2').type('-12.509').should(haveValue('-12.50'))
+        get('#2').type('{leftArrow}{leftArrow}{leftArrow}-').should(haveValue('-12.50'))
+        get('#2').type('{leftArrow}{leftArrow}{backspace}').should(haveValue('12.50'))
+        get('#2').type('{rightArrow}-').should(haveValue('12.50'))
+        get('#2').type('{rightArrow}-').should(haveValue('12.50'))
+        get('#2').type('{rightArrow}{rightArrow}{rightArrow}-').should(haveValue('12.50'))
+        get('#2').type('{leftArrow}{leftArrow}{leftArrow}{leftArrow}{leftArrow}-').should(haveValue('-12.50'))
+    }
+)