Skip to content

Commit

Permalink
Implement the directive of positive number (rancher#9451)
Browse files Browse the repository at this point in the history
  • Loading branch information
DaiYuzeng authored and Yonas Berhe committed Jan 26, 2024
1 parent adfe519 commit e826823
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
5 changes: 5 additions & 0 deletions shell/initialize/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import '../plugins/trim-whitespace';
import '../plugins/extend-router';

import intNumber from '../plugins/int-number';
import positiveIntNumber from '../plugins/positive-int-number.js';
import nuxtClientInit from '../plugins/nuxt-client-init';
import replaceAll from '../plugins/replaceall';
import backButton from '../plugins/back-button';
Expand Down Expand Up @@ -277,6 +278,10 @@ async function createApp(ssrContext, config = {}) {
await intNumber(app.context, inject);
}

if (process.client && typeof positiveIntNumber === 'function') {
await positiveIntNumber(app.context, inject);
}

if (process.client && typeof nuxtClientInit === 'function') {
await nuxtClientInit(app.context, inject);
}
Expand Down
7 changes: 5 additions & 2 deletions shell/plugins/int-number.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,12 @@ export default Vue.directive('intNumber', {
el.addEventListener('keypress', (e) => {
e = e || window.event;
const charcode = typeof e.charCode === 'number' ? e.charCode : e.keyCode;
const re = /\d/;
const inputChar = String.fromCharCode(charcode);

if (!re.test(String.fromCharCode(charcode)) && charcode > 9 && !e.ctrlKey) {
// Allow digits, minus sign at the beginning, and Ctrl key combinations
const re = /^-?\d*$/;

if (!re.test(inputChar) && charcode > 9 && !e.ctrlKey) {
if (e.preventDefault) {
e.preventDefault();
} else {
Expand Down
19 changes: 19 additions & 0 deletions shell/plugins/positive-int-number.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import Vue from 'vue';

export default Vue.directive('positiveIntNumber', {
inserted(el) {
el.addEventListener('keypress', (e) => {
e = e || window.event;
const charcode = typeof e.charCode === 'number' ? e.charCode : e.keyCode;
const re = /^\d+$/; // Use regex to match positive numbers

if (!re.test(String.fromCharCode(charcode)) && charcode > 9 && !e.ctrlKey) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
});
}
});

0 comments on commit e826823

Please sign in to comment.