Disable user of multiple same exact numbers in input box - javascript

I have an input box here
<input type="text" size="9" maxlength="9" id="my_account" name="my_account" value="" >
And I want to disallow users to enter the same numbers in the box? How can I do this ? Thanks in advance
I don't want them to be able to enter numbers like this
111111111
or
55555555

You can use a regular expression to find strings that only consist of one consecutive digit:
var validator = /\b(\d)\1+\b/
console.log(validator.test('111')) // true
console.log(validator.test('123')) // false
console.log(validator.test('121')) // false
console.log(validator.test('112')) // false

#edit If you don't want to let user enter these values as he types you may want to verify only when value equals to 2.
You can listen on keydown event of input element and verify it's actual content and pressed number like this:
var inputNode = document.getElementById('my_account');
inputNode.addEventListener('keydown', (event) => {
var inputValue = event.key;
var inputNodeValue = inputNode.value;
var length = inputNodeValue.length;
if (length === 1 && inputNodeValue[0] === inputValue) {
event.preventDefault();
}
});
If you want to verify on submit, just get value of first character and check if every other is equal to it.

Try this pattern:
<input type="text" size="9" maxlength="9" id="my_account" name="my_account" value="" pattern="^(?!(\d)\1{8}).*">
Notes:
you did not say you wanted to disallow letters, if you do, just replace .* with \d*
I interpreted it as "nine times the same number". If you want to e.g. not allow "3 times same number anywhere", you need to change it to ^(?!\d*(\d)\1{2,}).*
If you want to only disallow multiples of a digit without any other extra, add the line termination regex: ^(?!(\d)\1*$).*
Example for "not 3 times same number anywhere but must be numbers":
<input type="text" size="9" maxlength="9" id="my_account" name="my_account" value="" pattern="^(?!\d*(\d)\1{2,})\d*">
Example for "not only the same number multiple times but still numbers":
<input type="text" size="9" maxlength="9" id="my_account" name="my_account" value="" pattern="^(?!(\d)\1*$)\d*">

Related

Check if string that must be just numbers has characters

I have a input for phone number, and its type is not number is text, and I want to check if the input has characters to validate it as wrong, I have set it like that because I put a format to the input like 123-123-1234
here is my input
<input (keyup)="format()" (change)="format()" maxlength="12" inputmode="numeric" type='text' class="input" formControlName="celular" id="celular" name="celular">
Here is my ts where I set the format
format(){
$('#celular').val($('#celular').val().replace(/^(\d{3})(\d{3})(\d+)$/, "$1-$2-$3"));
}
so what I want to do, is to know if the value of my input has characters from aA-zZ and some specials characters that are not -
With a little help from google i found this:
Regex phoneRegex =
new Regex(#"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$");
if (phoneRegex.IsMatch(subjectString)) {
string formattedPhoneNumber =
phoneRegex.Replace(subjectString, "($1) $2-$3");
} else {
// Invalid phone number
}
You can use html regex pattern for validating input fields
Example:
Format used in this example is 123-123-1234
<form>
<input type="text" placeholder="Enter Phone Number in format (123-123-1234)" pattern="^\d{3}[-]\d{3}[-]\d{4}$" title="Invalid input" size="50" />
<button type="submit">Submit</button>
</form>
I have found the solution
var b = /[a-z A-Z]/
var a = '123a'
b.test(a)
this gives true or false depending if the var a has any character from a-z and A-Z

Check if Form Input is Valid With JavaScript

I am currently trying to make a login / create account page for a website that I am developing for fun. In the create account form, I have an input field for username, name, email, password, and verify password. I also have patterns in the input fields so that the user makes valid account info. Here is the form below:
<form method="post" action="CreateAccount.php">
<h1>Create Account</h1>
<input class="inputInfo" type="text" name="username" id="newUsername" pattern="[A-Za-z0-9]+" placeholder="Username" maxlength="40" minlength="5" onkeyup="checkInput()" onblur="checkInput()" autocomplete="off" required/>
<input class="inputInfo" type="text" name="fullname" id="newName" placeholder="First and Last Name" onkeyup="checkInput()" onblur="checkInput()" minlength="3" autocomplete="off" required/>
<input class="inputInfo" type="email" name="email" id="newEmail" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,}$" title="Must be a real email" placeholder="Email" onkeyup="checkInput()" onblur="checkInput()" required/>
<input class="inputInfo" type="password" name="password" id="newPassword" pattern="(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$" placeholder="Password"
title="Must be 8 or more characters with at least one number or special character, uppercase letter, and lowercase letter" onkeypress="checkInput()" onblur="checkInput()" required/>
<input class="inputInfo" type="password" name="verifypassword" id="verifyPass" pattern="(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$" placeholder="Verify Password"
title="Must be 8 or more characters with at least one number or special character, uppercase letter, and lowercase letter" onkeypress="checkInput()" onblur="checkInput()" required/>
<span><label for="showp"><input type="checkbox" id="showp" onclick="showPassword()">Show Password</label></span>
<button type="submit" style="margin-top: 7px;" class="disabled" id="submitButton">Sign Up</button>
<p style="font-size: 10px;">By signing up, you agree to our Terms , Data Policy and Cookies Policy .</p>
</form>
For clarification: the username pattern requires you to have a username with only upper and lower case letters and numbers and must be at least 5 characters and at most 40 characters. The email requires you to input a valid email address pattern. And the password requires a password that is at least 8 characters and must have an uppercase and lowercase letter and a number or special character.
In the input fields, you will see that I have a function called during blur or keyup event that is called checkInput(). The purpose of the function is to ensure that the input fields have the necessary length before the submit button can be enabled:
function checkInput ()
{
let usernameLength = document.getElementById('newUsername').value.length;
let nameLength = document.getElementById('newName').value.length;
let emailLength = document.getElementById('newEmail').value.length;
let passwordLength = document.getElementById('newPassword').value.length;
let verifyLength = document.getElementById('verifyPass').value.length;
if (usernameLength >= 5 && nameLength > 0 && emailLength > 0 && passwordLength >= 8 && verifyLength >= 8)
{
document.getElementById('submitButton').disabled = false;
const element = document.querySelector('#submitButton');
if (element.classList.contains('disabled'))
{
element.classList.remove('disabled');
}
}
else
{
document.getElementById('submitButton').disabled = true;
const addElement = document.querySelector('#submitButton');
addElement.classList.add('disabled');
}
}
I also have the following CSS classes that either make the border and shadow of the input field green or red:
.validInput {
border-color: #50c878;
box-shadow: 0 0 5px #50c878;
}
.invalidInput {
border-color: #ff0000;
box-shadow: 0 0 5px #ff0000;
}
My problem is that I would like to add some javascript so that while the user is typing in their information into the form, the code checks to make sure their input matches the patterns that are stated in the input fields. If the input they are putting into the field is valid, I would like for the javascript to add the validInput class to the input field. If the input is invalid I would like to add the invalidInput class to the input field. I have no idea, though, how to go about having JavaScript check if the input follows the pattern.
I would also like to make it to where it checks if the input is valid every time the user has a change event.
Does anyone have any ideas on how to go about doing this?
You can use the addEventListener function with 'change' parameter if you want your verification to run after the user leaves the field, or with 'input' parameter if you want the verification to run each time the user writes something in the text field. This should do it for you:
// If you want the verification to run when the user leaves the input.
document.getElementById('newUsername').addEventListener("change", checkInput);
// If you want the verification to run each time the user changes the input.
document.getElementById('newUsername').addEventListener("input", checkInput);
For the verification part, you can use regex. Create the verification functions first, (checks if the input is valid):
let check_username = (username)=>{
let rx = /^[a-z0-9]{8,40}$/i;
return rx.test(username); // Checks if the username is only made of alphanumeric characters (case insentisive)
}
let check_password = (password)=>{
let special_char = /[0-9!##\$%\^\&*\)\(+=._-]/; // If you want more special characters add them inside the braces at the end (after the '=+._-')
let upper_char = /[a-z]/;
let lower_char = /[A-Z]/;
return special_char.test(password) // Checks if the password contains a special character or a number
&& upper_char.test(password) // Checks if the password contains an upper case letter
&& lower_char.test(password) // Checks if the password contains a lower case letter
&& password.length>=8; // checks the password length
}
let check_email = (email)=>{
let rx = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+$/;
return rx.test(email); // Checks the mail format.
}
Then you can use them like that:
check_username(document.getElementById('newUsername').value)
// This should return true if the username is valid or false if not.
Hope this was helpful. You can close the subject if that's what you are looking for.

Slicing a string scanned from a bar-code into 2 input box

The HTML looks like this:
<div>
<label class="sr-only" for="product">Product</label>
<input id="product" type="text" placeholder="Product" maxlength="7" autofocus>
<label class="sr-only" for="batch">Batch</label>
<input id="batch" type="text" placeholder="Batch" maxlength="5">
</div>
The jQuery looks like this:
$('#product').on('keyup', function() {
let product = $(this).val().slice(0, 7);
let batch = $(this).val().slice(9, 14);
if ($(this).val() && $(this).val().length === 7) {
$(this).val(product);
$(this).next().focus().val(batch);
}
});
When I'm scanning the barcode, it reads this string WXYZ519 -8012456789.
I need to slice this string so that the input with id="product" and id="batch" gets the values as WXYZ519 and 80124 respectively without the hyphen and space in between.
The first input does receive the right value but I just couldn't get the second input to slice the right value into it.
Can anyone tell me why and what's wrong with my code?
Your range appears to be wrong if you wanted to get the entire 2nd half of the string.
If you change
$(this).val().slice(9, 14);
to
$(this).val().slice(9, $(this).val().length);
it will contain a string that starts at 9 and ends at the end of the string.
Another alternative which I believe is much cleaner and less error prone would be this:
let split = $(this).val().split(" -");
let product = split[0];
let batch = split[1];

Limit the user's input in an input number to 4 digits

How can I prevent (usign maybe Angular) the user from entering more than 4 numbers in a an simple number like this one :
<input type="number">
I used ng-maxlength, and max attributes, but those attributes as specified by w3.org specs and the official website Angular, do not prevent the user from adding more numbers.
What I want is that the input stops in 4 digits, like adding in somehow a mask or something to it.
Here is a way to do it using JavaScript:
HTML
<input type="number" oninput="checkNumberFieldLength(this);">
JavaScript
function checkNumberFieldLength(elem){
if (elem.value.length > 4) {
elem.value = elem.value.slice(0,4);
}
}
I would also suggest to make use of the min and max HTML attributes for the input Number element, if it applies in your case.
JSFiddle
W3c: input Number
Well, as somebody stated above maxlength doesn't work with inputs of type number, so you can do it this way:
<input type="text" pattern="\d*" maxlength="4">
of course, this will do if it's not a requirement to have input type="number"
Using ng-pattern with a regex
\d : digits
{4} : 4 times
<input type="number" ng-pattern="/^\d{4}$/" />
I would create a function in your controller like this
angular.module("my-app", [])
.controller('my-controller', function($scope) {
$scope.checkInput = function() {
if (input.value.length > 4) {
input.value = input.value.slice(0,4);
}
});
});
Then in your view you can do something like this
<input type="number" max="9999" ng-input="checkInput()" />
Warning: The max attribute will only work for the spinner. The user will still be able to enter numbers higher than that. Here's an example
<input type="number" max="9999" />
You can do that using modernizr and jquery.
I've made an example here: https://jsfiddle.net/5Lv0upnj/
$(function() {
// Check if the browser supports input[type=number]
if (Modernizr.inputtypes.number) {
$('input[type=number]').keypress(function(e) {
var $this = $(this),
maxlength = $this.attr('maxlength'),
length = $this.val().length;
if (length >= maxlength)
e.preventDefault();
});
}
});

user can enter in text box just numbers and this signs (, .)

I want to restrict user to enter in text box just numbers and this signs (, .) when the user try to enter letters or other signs textbox can't accept them How can I do that with jquery?
<input type="text" pattern="[0-9,.]+" title="Please enter only numbers" />
No jQuery needed. Demo
If you're actually looking for an optionally thousand-separated decimal number, try:
pattern="(?:[1-9][0-9]{0,2}(?:,[0-9]{3})+|[1-9][0-9]*)(?:\.[0-9]+)?"
Advanced demo
Be sure to do the same validation server-side!
jQuery not needed.
HTML:
<input type="text" id="ID">
JS:
document.getElementById("ID").onkeyup = function() {
var text_content = document.getElementById("ID").value;
if(/[^\-,0-9]/.test(text_content)) {
text_content = text_content.substring(0, text_content.length - 1)
document.getElementById("ID").value = text_content;
}
}
Fiddle. Hope that was what you were looking for.

Categories

Resources