This question already has answers here:
Not allow space as a first character and allow only letters using jquery
(4 answers)
Closed 4 years ago.
I have a name input filed that takes all the characters including space. I want to use regular expression to not allow first character to be a blank space. User must enter at least one valid character before they are allowed to enter space.
Thank you for you help.
I want to use regular expression to not allow first character to be a
blank space.
Instead of using regex you can just capture keys in the input and prevent space from being inserted when it's the first character entered.
document.getElementById("input").addEventListener('keydown', function (e) {
if (this.value.length === 0 && e.which === 32) e.preventDefault();
});
<input id="input"></input>
You should use trim to validate the extra space and then see if atleast a character is added or not.
let str = " ";
console.log(str);
if(!str.trim()) {
console.log("At least a character required");
} else {
console.log(str);
}
let correctStr = " a ";
if(!correctStr.trim()) {
console.log("At least a character required");
} else {
console.log(correctStr);
}
Do you mean to implement something like this? The first character can never be a space, it has to be some char, after the first char, then it can have infinite number of spaces after it.
const el = document.getElementById("demo");
// A function to encapsulate your logic.
const process = e => {
const v = el.value.toString().replace(/\ /g, '');
// Must have length > 0 before the space bar will do anything.
if (v.length == 0 && e.which == 32) e.preventDefault();
// First char must not be a space.
else if (el.value[0] == ' ') el.value = el.value.replace(/\ /, '');
};
// Do whatever here.
const onChange = () => {
el.onkeydown = process;
el.onkeyup = process;
};
// Lazy on ready..
setTimeout(onChange, 100);
<input id="demo" />
Related
I am trying to remove illegal characters from a user input on a browser input field.
const myInput = '46432e66Sc'
var myPattern = new RegExp(/^[a-z][a-z0-9]*/);
var test = myPattern.test(myInput);
if (test === true) {
console.log('success',myInput)
} else {
console.log("fail",myInput.replace(???, ""))
}
I can test with the right regex and it works just fine. Now I am trying to remove the illegal characters. The rules are, only lower case alpha character in the first position. All remaining positions can only have lower case alpha and numbers 0-9. No spaces or special characters. I am not sure what pattern to use on the replace line.
Thanks for any help you can provide.
Brad
You could try the below code:
const myInput = '46432e66Sc'
var myPattern = new RegExp(/^[a-z][a-z0-9]*/);
var test = myPattern.test(myInput);
if (test === true) {
console.log('success',myInput)
} else {
console.log("fail",myInput.replace(/[^a-z0-9]/g, ""))
}
Replace is using the following regexp: /[^a-z0-9]/g. This matches all characters that are not lowercase or numeric.
You can validate your regexp and get help from cheatsheet on the following page: https://regexr.com/
You could handle this by first stripping off any leading characters which would cause the input to fail. Then do a second cleanup on the remaining characters:
var inputs = ['abc123', '46432e66Sc'];
inputs.forEach(i => console.log(i + " => " + i.replace(/^[^a-z]+/, "")
.replace(/[^a-z0-9]+/g, "")));
Note that after we have stripped off as many characters as necessary for the input to start with a lowercase, the replacement to remove non lowercase/non digits won't affect that first character, so we can just do a blanket replacement on the entire string.
I am making a Signup form.
In that, I have a username field that should not allow the characters -, space, ", ' but I can't get that to happen.
I tried:- Slice method, substring method, regex, remove and split method and join technique.
So code:
function username(event) {
text = document.getElementById('usname').value;
key = event.key;
if (key == ' ' || key == '"' || key == "'" || key == '-') {
setTimeout(() => {
let final = text.slice(0, -1);
document.getElementById('usname').value = final';
},0.005)
}
}
This was my best approach was this but it removed two characters at once and if we spam space and then type a character, we get a space in the text which is invalid.
You can use regular expression [Regex]
This regex will accept only alphabets and numbers , and remove special characters and spaces.
function username(event) {
text = document.getElementById('usname').value;
document.getElementById('usname').value = text.replace(/[^a-zA-Z0-9\w]/g, "");
}
<input type="text" onkeyup="username()" id="usname" />
EDIT
[^a-zA-Z0-9\w] is the same as [^\w] or just \W. All will allow , so
[^a-zA-Z0-9] or [\W] would be better. – MikeM
You are right my friend, this much better.
function username(event) {
text = document.getElementById('usname').value;
document.getElementById('usname').value = text.replace(/[\W_]/g, "");
}
<input type="text" onkeyup="username()" id="usname" />
EDIT
I don't want other symbols to be removed I just want these:- the dash(-), space, single and double quotes(',"). – Shaurya Shrimal
Add the symbols you want to remove in regex /[-'" ]/g
function username(event) {
text = document.getElementById('usname').value;
document.getElementById('usname').value = text.replace(/[-'" ]/g, "");
}
<input type="text" onkeyup="username()" id="usname" />
First of all, to give the best user experience to the user, you should inform the user with a hint text below the input box saying that these characters are not allowed.
It is recommended to have a validation on the input box, which will warn the user by highlighting the input box as red when the user inputs invalid characters, and not allowing to submit, rather than removing the characters from their entry without their knowledge.
For form validation, use a library like validator for detecting invalid characters. Example for validating username that should have only alpha numeric characters:
validator.isAlphanumeric('fooBar123'); //=> true
I have the following javascript .match script to allow telephone numbers in form submit
var number = jQuery('#phone-number').val();
if ((number.match(/(\d)\1\1\1\1\1/))
|| (number.match(/(\d)(\d)\1\2\1\2\1\2/))
|| (number.match(/123456|234567|345678|456789|567890|987654|876543|765432|654321|543210/))
|| (!number.match(/^(0\d{8,10})?$/))) {
alert("Please supply a valid phone number");
return false;
}
Currently, it doesnt allow a SPACE between numbers.. I'm no good at regex and was wondering if someone could tell me how I allow a SPACE between any number using the script above?
thanks
Craig.
If you want to specify any number of spaces between each character, you can use \s*.
\s stands for whitespace character and * for any number of those
E.g.
\s*(\d)\s*\1\s*\1\s*\1\s*\1\s*\1\s*
const regex = /\s*(\d)\s*\1\s*\1\s*\1\s*\1\s*\1\s*/;
const tel1 = '111111';
const tel2 = ' 1 1 1 1 1 1';
console.log(regex.test(tel1));
console.log(regex.test(tel2));
Ugly, but:
if ((number.match(/(\d)\s*\1\s*\1\s*\1\s*\1\s*\1\s*/))
|| (number.match(/(\d)\s*(\d)\s*\1\s*\2\s*\1\s*\2\s*\1\s*\2\s*/))
|| (number.match(/123456|234567|345678|456789|567890|987654|876543|765432|654321|543210/))
|| (!number.match(/^(0(?:\s*\d\s*){8,10})?$/))) {
alert("Please supply a valid phone number");
return false;
}
For 1 space only replace \s* with \s?
You can remove all spaces from a string with
str = str.replace(/\s/g, '');
Then you can use your existing code.
I need to block special character except comma. So I am using code given below. Its is working but it is also removing space between two words. fiddle
var chars =/[(,\/\w)]/i;
$('input').keyup(function(e) {
var value = this.value;
var char = value[value.length-1];
if(char !== ' ' || value.length==1 || (value[value.length-2]!==' ' )){
if (!chars.test(char)) {
$(this).val(value.substring(0, value.length-1));
}
}
});
In terms of usability, manipulating the user's input as they're typing can be very frustrating. In addition, if the user types fast enough it doesn't work anyway (as mentioned by Daniel Knippers, above)
A better bet would be to validate the user's input and let them know in real-time if the input is invalid.
Try this code:
var regex =/^[\w\s\,]*$/i;
$('input').keyup(function(e) {
var message = regex.test(this.value) ? "" : "Error";
$('#message').html(message);
});
jsFiddle version
as far as i am understood, you wants that space should be allowed in txt box
so,
here is your ANSWER
you need to add space after \w
var chars =/[(,\/\w )]/i;
$('input').keyup(function(e) {
var value = this.value;
var char = value[value.length-1];
if(char !== ' ' || value.length==1 || (value[value.length-2]!==' ' )){
if (!chars.test(char)) {
$(this).val(value.substring(0, value.length-1));
}
}
});
please note that i have added space after \w, so the regexp is var chars =/[(,\/\w )]/i;
I have an input box where the a username is input'd but if invalid characters are input'd, I want it to error. The code below is what I'm using; What would i put in the "something" section?
var numbers = new RegExp("SOMETHING");
$(this).removeClass("active");
if(($(this).val() == "") || $(this).val().match(numbers))
{
$("#firstNameErrorMsg").html("First name can only contain letters. ");
}
else
{
$("#firstNameErrorMsg").html("OK");
}
Here are some patterns I wrote them long years ago:
patt['name'] = /^[a-z ,-]+$/i;
patt['username'] = /^[A-z0-9_-]+$/i;
patt['email'] = /^[a-z0-9]+(?:[\.-]?[a-z0-9]+)*#[a-z0-9]+([-]?[a-z0-9]+)*[\.-]?[a-z0-9]+([-]?[a-z0-9]+)*([\.-]?[a-z]{2,})*(\.[a-z]{2,5})+$/i;
patt['website'] = /^http(s)?:\/\/(www\.)?[a-z0-9]+([-]?[a-z0-9]+)*[\.-]?[a-z0-9]+([-]?[a-z0-9]+)*([\.-]?[a-z]{2,})*(\.[a-z]{2,5})+$/i;
patt['age'] = /^(?:([1][3-9]|[2-9][0-9]))$/i;
patt['subject'] = /[a-z0-9?!:;'&_\. ,-]+/i;
If you want to use them, you should check this condition:
if(($(this).val() == "") || ! $(this).val().match(patt['name'])){ // in case.
...
}
But if you want to check undesirable characters, it'll be a long pattern for username input.
Try this Regex
[A-Za-z]
This will match only lowercase and uppercase characters
Suggest you read a bit about regexes and experiment with them.
To get simply letters and nothing else, just do:
^[a-zA-Z]+$
That allows 1..n lowercase & uppercase letters to be found between start and end, nothing else. Sushanth's version will match partial pieces of the input, letting the user to use spaces, numbers, etc. elsewhere as long as there's one piece of of the input with a word in it.
This should be a full implementation of what you're trying to do:
var invalid = /[^A-Za-z]+/;
$(this).removeClass("active");
if($(this).val() == "" || invalid.test($(this).val()))
{
$("#firstNameErrorMsg").html("First name can only contain letters. ");
}
else
{
$("#firstNameErrorMsg").html("OK");
}
Sushanth is mostly correct, but you will need to match any number of letters, and it has to be from the start to the end only letters, so you should do something like this
var name = new RegExp('^[A-Za-z]+$');
$(this).removeClass('active');
if($(this).val().match(name)) {
$('#firstNameErrorMsg').html('OK');
} else {
$('#firstNameErrorMsg').html('First name can only contain letters.');
}
If you are looking for validating your users input , to only have letters , i would suggest using the char code, something like this :
add the keypress event on the input tag
for the event args passed, check the character code (Some browsers use keyCode, others use which)
function checkOnKeyDown(event){
if (event.KeyCode >= 65 && event.keyCode <=122)
{
//all ok here -- only upper/lowercase letters accepted
}
else
{
//wrong
}
}
Here is a list with all the keyCode to characters mapping ;) : http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes