Regex with imask.js - javascript

I'm trying to create a Mask on my input so that the user is forced to enter a value in the format 'YYYY Text' (YYYY being a year but I can not check its validity, I just check that they are numbers). My problem is that it is not working with this regular expression that is good :
var element = document.getElementById('Cline');
var maskOptions = {
mask: /^[0-9]{4} [a-zA-Z]+$/
};
var mask = IMask ( element, maskOptions );
Here is the HTML of my input:
<input type="text" class="field__form-input" id="Cline" name="Cline">
the problem is that for example, the mask works with an expression that I took from the website which is this one:
var element = document.getElementById('Cline');
var maskOptions = {
mask: /^[1-6]\d{0,5}$/
};
var mask = IMask(element, maskOptions);
but when I put the news, the input is blocked and I can no longer write anything in it, as if no character was accepted. And yet the one I put is correct because I tested it without the mask on another input, and there no worries

Make sure that your regular expression accepts any prefix of a valid input, as also the imask documentation highlights.
It is important to realise that the user will enter the input character by character, and at each instance the input should be allowed when it can lead to a valid input when completely entered. Currently that is not the case as your regex requires the 4 digits, the space and at least one letter, which does not allow that the user enters a first digit, and so they cannot enter anything.
So do this:
mask: /^(\d{0,4}|\d{4} [a-zA-Z]*)$/
Snippet:
var element = document.querySelector('input');
var maskOptions = {
mask: /^(\d{0,4}|\d{4} [a-zA-Z]*)$/
};
var mask = IMask(element, maskOptions);
<script src="https://cdnjs.cloudflare.com/ajax/libs/imask/6.4.3/imask.min.js"></script>
<input>

Related

How do i prevent entering in input any character except letters and one underscore in a row?

I can't create an input in which the first character entered must be a letter, and the following characters can be only letters or only one underscore in a row
i have an input and following javascript code for it:
var nick = document.getElementById('donate-nickname');
function validatenick(evt) {
var regex = /^[a-zA-Z][a-zA-Z_]*$/;
if(!regex.test(nick.value)) evt.preventDefault();
}
nick.onkeydown = validatenick;
nick.onpaste = validatenick;
but it doesn't work
Some issues:
You are not assigning visited to onkeydown, but instead execute it. (You fixed this after I posted this answer)
input.value will reflect the input as it is before the key was processed, so the validation check comes too early.
The regex does not implement the logic you describe
I would suggest a regex where you perform a negative look-ahead for a double underscore. Also make it allow empty input as else the user cannot delete the last character that remains in the input.
For responding to all input methods, use the input event. Then to cancel the edit that would break the pattern, you could keep track of the most recent input that was still valid, and when there is a violation of the pattern, roll back to that value:
var input = document.getElementById('nickname');
var lastValid = "";
function validate(evt) {
var regex = /^(?!_)(?!.*?__)[A-Za-z_]*$/;
if(!regex.test(input.value)) {
input.value = lastValid;
}
lastValid = input.value;
}
input.oninput = validate;
<input id="nickname">
As a side note, I would personally not block edits like that: users may wrongly think their keyboard is malfunctioning. It is better practice to let the user type what they want, but accompany it with feedback (coloring, an error message, ...).

Input box onchange only allow numbers and one dot

I am creating an input box with an onChange function that will check to see if the characters are only digits and only allow up to one period/dot '.'
The function I have here is not working:
function addPercentSeparator(n) {
let str = n;
let match = str.match(/\d*\.\d*/)
if (match) {
return str;
}
}
I also tried: let match = str.match(/^([0-9]+(\.[0-9]+)?)/)
What I am trying to achieve is only allowing for one period.
If the user enters a number without a period, it will append a period to end of string when they click outside the input box.
This regex is supposed to do the trick:
^\d*\.?\d*$
But if you'll ask me, I would make sure there are digits before the dot, using ^\d+\.?\d*$.
Explanation:
As the dot isn't mandatory, I've added the ?, which symbolizes "0 or 1 occurrences".
I've also added the ^ and the $ to make sure no parts of the string will be matched if the whole string is illegal.
I hope this works for you!

Detecting characters on keypress

Let say in the text input field, I am typing a sentence. Then I input a certain character, for example, "#" like below:
I am writing this example with # symbol.
Using the keypress, when the symbol is used, I want to check the character before and after it.
In this case, it will give two empty spaces.
Another example is:
This is another example using #text.
Here it should give a space as "before" and "t" for "after" the symbol.
How would I detect these characters when keypress condition is met?
Any suggestion will be much appreciated.
Use the input event in conjunction with the selectionStart property on your input element, which allows you to get the position of the cursor.
document.getElementById('example').addEventListener('input', function () {
var text = this.value,
cursor = this.selectionStart
// the characters in question
var previous = text.charAt(cursor - 2),
current = text.charAt(cursor - 1),
next = text.charAt(cursor)
// do something cool
console.log(previous, '|', current, '|', next)
})
<input type="text" id="example" value="edit this example text :)"/>

Alphanumeric JavaScript RegEx for Password Validation

I'm using a regex below to validate password to accept alphanumeric characters only. The regex works if I enter 2 characters one alpha and one number but if more than two characters my regex doesn't work. I want if possible the following results as shown in "Expected Behavior". Can anyone help me rewrite my regex?
JavaScript
function checkPasswordComplexity(pwd) {
var regularExpression = /^[a-zA-Z][0-9]$/;
var valid = regularExpression.test(pwd);
return valid;
}
Current Behavior
Password:Valid
a1:true
aa1:false
aa11:false
Expected Behavior
Password:Valid
aa:false (should have at least 1 number)
1111111:false (should have at least 1 letter)
aa1:true
aa11:true
a1a1a1a1111:true
You want to add "one or more", you're currently checking for a letter followed by a number.
Try:
/^[a-zA-Z0-9]+$/
+ means 'one or more'
I also joined the ranges.
Note: I don't understand why you'd want to limit the password to such a small range though, having a wide character range will make your passwords stronger.
Here is a fiddle demonstrating the correct behavior
If you just want to validate that the password has at least one letter and at least one number, you can check like this:
function checkPasswordComplexity(pwd) {
var letter = /[a-zA-Z]/;
var number = /[0-9]/;
var valid = number.test(pwd) && letter.test(pwd); //match a letter _and_ a number
return valid;
}
function checkPasswordComplexity(pwd) {
var regularExpression = /^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$/;
var valid = regularExpression.test(pwd);
return valid;
}
You can use this:
/^(?=.*\d)(?=.*[a-z])[a-z\d]{2,}$/i
Try doing this:
var regularExpression = /^[a-zA-Z0-9]+$/;
This means "one or more letter or number."
However, some users might also want to enter symbols (like &*#) in their passwords. If you just want to make sure there is at least one letter and number while still allowing symbols, try something like this:
var regularExpression = /^(?=.*[a-zA-Z])(?=.*[0-9]).+$/;
The (?=.*[a-zA-Z]) is a positive lookahead. This means that it makes sure that there is a letter ahead of it, but it doesn't affect the regex.
{
var pwd=document.getElementById('pwd').value;
var reg = /^[a-zA-Z0-9]{8,}$/;
var re=reg.test(pwd);
alert(re);
}
I think lookaround aren't supported by javascript, so you can use:
^([a-zA-Z]+\d+)|(\d+[a-zA-Z]+)
But if they are supported:
/^(?=.*\d)(?=.*[a-zA-Z])[a-zA-Z\d]{2,}$/

What is the best way to limit text input entry to numbers, lowercase letters, and certain symbols?

Without using jQuery, what is the best way to limit text entry of a textbox to numbers, lowercase letters and a given set of symbols (for example - and _)? If the user enters an uppercase letter, I would like it to be automatically converted to a lowercase letter, and if the user enters a symbol not within the given set, I would like to be able to instantly show a validation error (show some element adjacent to or below the text box).
What's the cleanest cross-browser way of doing this without the aid of jQuery?
Attach the following to your elements onkeyup event.
function onkeyup()
{
var el = document.getElementById("id"); // or however you want to get it
el.value = el.value.toLowerCase(); // covert to lower case
if (el.value.match(/[^-\d\w]/)) // check for illegal characters
{
// show validation error
...
// remove invalid characters
el.value = el.value.replace(/[^-\d\w]/g, "");
}
else
{
// hide validation error
}
}
The regex matches any character which is not a digit, a letter, a hyphen or an underscore.

Categories