How to hide password with emoji instead of an asterisk (VueJS) - javascript

I created two variables: password (the real password is stored there that will be sent to the server) and emojiPassword, which will store the hidden password in the input field as random emoji (look at an example). But the problem is that event.target.value takes emojis instead of a real password (look at here). Any ideas how to prevent this?
data() {
return {
password: null,
emojiPassword: ""
};
},
My full code:
<template>
<div class="container">
<form #submit.prevent>
<label for="password">Password</label>
<input
:value="emojiPassword"
#input="changeHandler($event)"
type="text"
id="password"
name="password"
/>
</form>
</div>
</template>
<script>
export default {
data() {
return {
password: null,
emojiPassword: ""
};
},
methods: {
changeHandler(event) {
this.password = event.target.value;
const emoji = [
"😀",
"😁",
"😂",
"🤣",
"😇",
"😋",
"😆",
"😅",
"🤑",
"🙃"
];
const randomNum = (min, max) => {
return min + Math.floor((max - min) * Math.random());
};
let passwordToConvert = event.target.value;
const emojiPassword = [...passwordToConvert].map(character => {
character;
return emoji[randomNum(0, 9)];
});
this.emojiPassword = emojiPassword.join("");
}
}
};

simple approach is:
use the text type input. on keyup change, when letter added, push letter (last letter) in certain array (xyz) and replace that in input field (with emoji randomize). and when a letter removed from input field, remove from certain array(xyz).
finally get certain array and merge element and send to server as password.

I think you can't do that, the length of the value you want is not accessible / inconsistent.
Because every time you emit an input (type) you will get the real value from input text.
And for the length calculation emoji is different with char, 6 char is not equal with 6 emoji. for example:
"garuda" you'll get length for 6
"😀😁😂🤣😇🙃" you'll get length 12
So, when you type first char it will replace with first emoji. And the next you type you will get first emoji and the last char you typed, which is when you calculate the length it will not get 2 char but about 3.

Related

Vue3/Javascript - Unable to create an input that only excepts numbers

I have a project with a input that only excepts numbers.
Inside the template I have defined a input with the value set to the variable that is being changed and the input being set to the function that checks if it is a number:
<input
:value="ie"
#input="(evt) => changeIE(evt)"
type="number"
min="0"
/>
Then in the setup function I have declared a ref ie. This contains the actual value that is being set by the input. I also have declared the `changeIE' function. Here I first get the input text from the evt. Then I check if the last entered character is a number. If not I remove the last character from the string. The next step is to parse the string to an Integer. And lastly I set the value of the variable to the new value of the input.
const ie = ref('');
const changeIE = (evt) => {
let value = 0;
let input = evt.target.value;
let isnum = /^\d+$/.test(input[input.length - 1]);
if (!isnum) input = input.slice(0, -1);
if (input !== '') value = parseInt(input);
ie.value = value;
};
The problem is that the input keeps on excepting non numerical numbers even tough I check if they are numbers and if not I remove that character from the string.
Try to use the v-model with number as modifier and set initial value to 0 :
<input
v-model.number="ie"
type="number"
min="0"
/>
and :
const ie=ref(0)
DEMO
try
const ie = ref(null) // instead of ref('')
By default you set it to a string

How to prevent the input field from accepting more than 2 decimal places in react native?

Restrict input field from accepting more than 2 decimal places. In most of the places, This is recommended, But instead of validating later, I dont want to allow more than 2 decimal places in the input field itself.
var validate = function(e) {
var t = e.value;
e.value = (t.indexOf(".") >= 0) ? (t.substr(0, t.indexOf(".")) + t.substr(t.indexOf("."), 3)) : t;
}
</script>
</head>
<body>
<p> Enter the number</p>
<input type="text" id="resultText" oninput="validate(this)" />
You could try this.
Set up your state for the input: const [value, setValue] = useState()
Then in your TextInput callback onChangeText, set it up like this.
onChangeText={(text) => {
const validated = text.match(/^(\d*\.{0,1}\d{0,2}$)/)
if (validated) {
setValue(text)
}
}}
This validates a string first to match the following pattern:
zero or more digits
followed by 0 or 1 decimal place
followed by 0, 1, or 2 decimal places (but no more than 2)
I also start the regex with a ^ which forces the match to start at the beginning of the text.
The text argument that is passed in to onChangeText is the entire string (not just the next character). If this string doesn't conform to the regex we set up (validation) then we ignore this value and the state isn't updated.
I'm sure there are other ways to do this, but this one worked for me.
Let me also add this: in React Native's TextInput you can control the keyboard type. Mine is set to a numeric keyboard so the user never gets a chance to enter a letter. This should work either way. It's just a side note
<input pattern='d\+\.\d\d$'/>
You can specify a regex pattern on the input and tell it to only accept numbers (\d), along with a dot and only two numbers after the dot.
I have no idea if that works in react native, only in browsers.
You don't necessarily have to resort to regex.
You can simply use conditionals of substrings on top of regex.
const onChangeText = (text) => {
// Only allow "number & ." input
const cleanNumber = text.replace(/[^0-9.]/g, "")
// Only take first 2 values from split. Ignore the rest.
const strAfterDot = cleanNumber.split('.', 2)[1]
if (strAfterDot.length <= 2){
console.log("setValue now")
setValue(text)
} else {
console.log("Should not be allowed. You can trim the value yourself.)
const strBeforeDot = cleanNumber.split('.', 1)[0]
setValue(strBeforeDot + '.' + strAfterDot.substr(0, 2))
}
}
(Not tested for edge-cases, I'll leave that up to you.)

Prevent invalid formats based on given regex

I have a regex for a set of use cases
Based on that regex I'm trying to prevent the user to type invalid formats.
The regex works and preventing the user adding invalid formats also works.
The part with which I'm struggling now is that if the default value is invalid, the user cannot add additional valid characters.
Here is what I have: http://jsfiddle.net/jgqco7by/2/.
<input id="myInput" type="text" value="co vi1d-" />
var previousValue = document.getElementById('myInput').value;
var pattern = /^[a-zA-Z]+(?:[ -][a-zA-Z]+)*([ ]|[-])?$/g;
function validateInput(event) {
event = event || window.event;
var newValue = event.target.value || '';
if (newValue.match(pattern)) {
// Valid input; update previousValue:
previousValue = newValue;
} else {
// Invalid input; reset field value:
event.target.value = previousValue;
}
}
document.getElementById('myInput').oninput = validateInput;
In this example since I have a default value which contains a number, which is not allowed, everything I type is replaced with previous value because the regex keeps coming back as invalid.
How could I build this so that, if the default value is invalid, the user can still add additional VALID values without having to remove the default invalid values first?
If you want to have the invalid data and a valid one in the same input I'm not seeing how it will happened with your approach.
If you want to have an initial value (that can be either valid or invalid) and then to append something (which is valid) then why are you checking for the initial state.
The third variant is to have both
Empty field and putting a valid chars only
Initial value (valid or invalid) and appending something (valid)
And the result will be to have a valid stuff.
Please place your question / requirement in a more structured manner.
As for the code I would suggest to change your regex. I can give suggestions for modification. :)
For the code:
<input id="myInput" type="text" value="co vi1d-" />
<p id="messageField"></p>
(function() {
const pattern = new RegExp(/^[a-zA-Z]+(?:[ -][a-zA-Z]+)*([ ]|[-])?$/g);
const messageField = document.getElementById('messageField');
function validateInput(event) {
var newValue = event.target.value; // no sense to have a check and to overwrite with window.event , its a different context
messageField.innerText = pattern.test(newValue) ? '' : 'incorrect input'; // its better to use test() method rather than match()
}
document.getElementById('myInput').oninput = validateInput;
}());

How to change user English number to Persian/Arabic instantly after user writes in the input tag?

i'm using Vuejs and I want to prevent input tag from showing user's characters and replace it with my own characters(which is some numbers).
I have already used #onchange and Watch and also getters and setters in computed. the problem is the character instantly appears on input and then changes to what i want.
<input v-model="phonenumber" id="downloadlink" v-
on:keydown="sendDownloadLink" placeholder=""
maxlength="11" autocomplete="off"
>
and in methods:
sendDownloadLink(e){
this.phonenumber = this.toPersianNum(this.phonenumber);
}
Thanks in Advance.
There are a few problems here that are difficult to overcome:
Only the input event is a reliable. Keyboard events won't necessarily fire if the value changes by copy/paste or drag/drop.
The input event fires after the input has been updated, so the characters the user types will be seen, albeit briefly, until the event listener can change them.
If the user changes characters in the middle of the value the position of the text cursor will jump to the end when updating the value to use the new numerals.
One way this could be approached is by using a font that shows the desired numerals for the characters 0 to 9. This would dodge most of the difficulties.
The code below attempts a JavaScript solution instead. It uses the input event as a catch-all. To try to prevent the wrong characters showing temporarily it cancels the keypress event and makes the necessary changes to the value itself. In all cases it tries to preserve the position of the text cursor using setSelectionRange.
This is not a particularly good demonstration of 'correct' Vue usage but I'm not sure the functionality can be achieved without resorting to direct DOM manipulation.
new Vue({
el: '#app',
data() {
return {
phoneNumber: ''
}
},
methods: {
getInputValue() {
const input = this.$refs.input
const value = input.value
const start = input.selectionStart
const end = input.selectionEnd
return [
value.slice(0, start), // before selection
value.slice(start, end), // selection
value.slice(end) // after selection
]
},
onInput() {
this.setInputValue(...this.getInputValue().map(this.toArabicNumerals))
},
onKeyPress(ev) {
ev.preventDefault()
const [before, , after] = this.getInputValue()
const keyValue = this.toArabicNumerals(ev.key)
this.setInputValue(before + keyValue, '', after)
},
setInputValue(before, selection, after) {
const input = this.$refs.input
const start = before.length
const end = start + selection.length
this.phoneNumber = input.value = before + selection + after
input.setSelectionRange(start, end)
},
toArabicNumerals(str) {
return str.split('').map(chr => {
if ('0' <= chr && chr <= '9') {
return String.fromCharCode(+chr + 1632)
}
if ('\u0660' <= chr && chr <= '\u0669') {
return chr
}
return ''
}).join('')
}
}
})
<script src="https://unpkg.com/vue#2.6.10/dist/vue.js"></script>
<div id="app">
<input
ref="input"
:value="phoneNumber"
#input="onInput"
#keypress="onKeyPress"
>
</div>
You may find that you can remove the onKeyPress listener altogether. On the hardware I had available for testing it didn't seem to make any difference but that might not be true for slower machines. The method setInputValue updates the <input> element's value directly and it may be that that is sufficient to get the desired results without the need for onKeyPress.

How do I restrict input in the ion-input?

I am trying to restrict the user of inputting numbers by removing and not visualizing them.
in html
<ion-input type="text" [(ngModel)]="firstName" (ionChange)="check($event)"></ion-input>
in .ts
check(event){
let value : string = event.detail.value;
event.detail.value = value.replace(/[0-9]/g,'')
}
With this code I expected for the user not to see if he inputs numbers. However the value of firstName changes, but the user still sees characters and numbers.
create one function
public onKeyUp(event: any) {
let newValue = event.target.value;
let regExp = new RegExp('^[A-Za-z? ]+$');
if (! regExp.test(newValue)) {
event.target.value = newValue.slice(0, -1);
}
}

Categories

Resources