Regex to prevent accented letters in the input - javascript

I want to block the entry of accented letters (any language) in input, preferably I would like this block to be done with regex through the attribute pattern
I tried something but I did not succeed...
<form>
<label for="username">Name <i>(only letters without accent)</i></label>
<br>
<input name="username" id="username" type="text" pattern="[A-Za-z]+" oninvalid="this.setCustomValidity('Only letters without accent')">
</form>
Accepts: Joao Silva, Pedro, Fabio Duarte...
Rejects: João Silva, Pedro Camões, Fábio Duarte ...

<input name="username" id="username" type="text"
pattern="[A-Za-z ]*" title="Latin letters and space characters only"> />
Test this code here.
Alternatively, you can control what characters are allowed during typing.
<input name="username" id="username" type="text" onCopy="return false"
onDrag="return false" onDrop="return false" onPaste="return false"
autocomplete=off />
jQuery:
$(document).ready(function() {
$("#username").keypress(function(event) {
var inputValue = event.which;
if(!((inputValue >= 65 && inputValue <= 90) || // A-Z
(inputValue >= 97 && inputValue <= 122) || // a-z
(inputValue == 32))) { // space
event.preventDefault();
}
});
});
Test this code here.

Original Answer
As specified in the question, it sounds like you want to block anything other than basic Latin alphabet letters and spaces, which is doable with a pattern attribute - the regex is ^[a-zA-Z ]+$.
Edit 2020-08-19
The question asks specifically about "accented letters", not non-Latin-alphabet characters or non-ASCII characters. As of 2020, and assuming you don't need to support Internet Explorer, this is actually fairly simple to check for in JavaScript.
Explanation
NFD normalization splits apart all diacritics from their base characters. The regex /\p{M}/u matches anything in the Unicode "Mark" category, such as all those diacritics we just split apart.
const hasDiacritics = str =>
/\p{M}/u.test(str.normalize('NFD'))
// tests
;[
'Joao Silva',
'Pedro',
'Fabio Duarte',
'João Silva',
'Pedro Camões',
'Fábio Duarte',
'Αρσένιος',
'Αρσενιος',
'Александра',
'李晓华',
].forEach(str => {
console.log(str, hasDiacritics(str))
})
You could use a similar method to strip diacritics:
const stripDiacritics = str =>
str.normalize('NFD').replace(/\p{M}+/gu, '')
stripDiacritics('ZA̡͊͠͝LGΌ ISͮ̂҉̯͈͕̹̘̱ TO͇̹̺ͅƝ̴ȳ̳ TH̘Ë͖́̉ ͠P̯͍̭O̚​N̐Y̡ H̸̡̪̯ͨ͊̽̅̾̎Ȩ̬̩̾͛ͪ̈́̀́͘ ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͥͮ͟Oͮ͏̮̪̝͍M̲̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔̀ͅ')
// => "ZALGΟ IS TOƝy THE PO​NY HE COMES"
Caveats
As pointed out in the article #Stephen P links to in the comment below, this is probably a bad idea. It's worth thinking carefully about whether you want to risk annoying or even offending your users by forcing them to enter something that isn't their real name.

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

How can I use javascript to index input from a HTML form?

I have a form where you must enter a username, but the username cannot start or end with a period (.). This is what I have so far, I feel like I'm close. I think I am making an error in the .value[0] parts.
//Checking Username
if (document.getElementById("uName").value[0] == "." || document.getElementById("uName").value[-1]) {
document.getElementById("notification4").innterHTML ="Cannot have period at start or end.";
submitForm = false;
} else {
document.getElementById("notification4").innerHTML="";
}
My second question is how would I be able to stop the same character from repeating twice in a row? For example you can't have (--) , (//), (%%), (**) etc. I would prefer a similar method to use like above or with regex.
This is the forms HTML:
<label for="uName"> Username: </label><br>
<input type="text" id="uName" name="uName"> <br>
<div class= "error" id="notification4"></div><br>
You can use regular expression and the RegExp.prototype.test() function:
const regex = /^[.]|[.]$|[^a-zA-Z0-9]{2}/g;
if(regex.test(str)) {
//code when it matches
} else {
//code when it doesn't match
}
This checks if the first or last character is a dot (^[.]|[.]$) and if there is any character repeated twice that is not a letter or number ([^a-zA-Z0-9]{2}).

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.

Disable user of multiple same exact numbers in input box

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*">

javascript validation for home address. Ex: #55 Bernahrd Gym

I need a validation for address that can have Numbers, alphabets, space in two words should be able .. but no space in the beginning of the address.
The only symbol should be #
EX: #55 Bernahrd Gym
Address:<input type="text" required="required" name="baguio_add"><br>
You can use regular expressions for this: /[a-z0-9\s\#]+/i
Instead of testing for spaces at the start, just use trim (or ltrim).
Edit: You changed your tag to Javascript, you can still use regular expressions for this using the regex above.
You can use this regex if you want only one #, and any number of alpha numeric plus spaces.
/#?[a-zA-Z\s\d]+/
If it always starts with # then:
/^(#?)[a-zA-Z\s\d]+$/
Here is how you use it:
HTML:
<input name="address" id="address" type="text" />
Javascript:
document.getElementById('address').onblur = function (e) {
console.log(this.value);
var isValid = /^(#?)[a-zA-Z\s\d]+$/.exec(this.value);
if (isValid){
// do any action on valid
this.className = 'valid';
} else {
this.className = 'invalid';
}
}
Here is a working example in jsfiddle: https://jsfiddle.net/uua6pp1q/

Categories

Resources