How do I restrict input in the ion-input? - javascript

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);
}
}

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 hide password with emoji instead of an asterisk (VueJS)

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.

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 put function using string control

On this first Image I would like to declare a variable that is string that would be used for making a condition if the username that is input if the string has 5 numbers it would be tag as EmployeeID if string has 10 numbers it would be tag as studentID.
So that before I create another app for User Interface for Employee and Student it would then evaluate.
I am not able deduce the code language, but I will write down a function considering that it's a jQuery.
var Id = "" , type = "";
if($("#Userid").val().length = 5)
{
Id = $("#Userid").val();
type = "employee";
}
elseif($("#Userid").val().length = 10)
{
Id = $("#Userid").val();
type = "student";
}
else
{
alert("Invalid ID");
}
Hope that's help! Now you can check type variable to decide the type of current logged in user.

Extract substring out of a user input phone number using Javascript

I am getting phone number input from user as +XXX-X-XXX-XXXX that (+XXX as country code), (X as city Code), (XXX as 1st 3 digits) and , (XXX as 2nd 4 digits). I used regular expression to confirm the entry as in following code;
function validate(form) {
var phone = form.phone.value;
var phoneRegex = /^(\+|00)\d{2,3}-\d{1,2}-\d{3}-\d{4}$/g;
//Checking 'phone' and its regular expressions
if(phone == "") {
inlineMsg('phone','<strong>Error</strong><br />You must enter phone number.',2);
return false;
}
if(!phone.match(phoneRegex)) {
inlineMsg('phone','<strong>Error</strong><br />Enter valid phone <br />+xxx-x-xxx-xxxx (or) <br />00xxx-x-xxx-xxxx.',2);
return false;
}
return true;
}
Its working very fine but the problem is that
EDIT : If the user inputs as +XXXXXXXXXXX (all together) and hit enter or go to another field, the input it self set according to the Regex that is +XXX-X-XXX-XXXX.
Can some one guide me with some example how to do this task.
Thank you
Set the element's onblur method a callback as follows:
var isValidPhoneNumber = function(string) {
...
}
var reformat = function(string) {
/*
* > reformat('example 123 1 1 2 3 123-45')
* "+123-1-123-1234"
*/
var numbers = string.match(/\d/g);
return '+' + [
numbers.slice(0,3).join(''),
numbers.slice(3,4).join(''),
numbers.slice(4,7).join(''),
numbers.slice(7,11).join('')
].join('-');
}
var reformatPhoneNumber = function() {
var inputElement = this;
var value = inputElement.value;
if (isValidPhoneNumber(value))
inputElement.value = reformat(inputElement.value);
else
// complain to user
}
Here are two example ways you could set the onblur callback handler:
document.getElementById('yourinputelement').onblur = reformatPhoneNumber;
<input ... onblur="reformatPhoneNumber"/>
You can augment reformatPhoneNumber with more validation code if you'd like, or just constantly validate the number as the user is typing it.
To only do this if your phone number is of the form +ABCDEFGHIJK, then add an string.match(/^\+\d{11}$/)!==null to your if statement. (^,$ mean the start and end of the string, \+ means a plus sign, and \d means a digit 0-9, repeated exactly {11} times). Specifically:
function isPlusAndEleventDigits(string) {
/*
* Returns whether string is exactly of the form '+00000000000'
* where 0 means any digit 0-9
*/
return string.match(/^\+\d{11}$/)!==null
}
Try shaping the input:
result = subject.replace(/^((\+|00)\d{2,3})-?(\d{1,2})-?(\d{3})-?(\d{4})$/mg, "$1-$3-$4-$5");
Then do next procedure.

Categories

Resources