In Javascript I tried to add a function like this for checking if the entered password contains any symbol (special) character such as !##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?.
So I did this:
function checkpasswordlength(){
var format1 = /^[!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*$/;
var e = document.getElementById("password").value;
if(e != "") {
if(e.length >= 12){
if(e.match(format1)){
document.getElementById("passwordstrengthstatus").style.display = "inline";
document.getElementById("passwordstrengthstatus").innerHTML = "strong";
document.getElementById("passwordstrengthstatus").style.setProperty('background-color', '#3cb878', 'important');
}else{
document.getElementById("passwordstrengthstatus").style.display = "inline";
document.getElementById("passwordstrengthstatus").innerHTML = "normal";
document.getElementById("passwordstrengthstatus").style.setProperty('background-color', '#3cb878', 'important');
}
}else{
document.getElementById("passwordstrengthstatus").style.display = "inline";
document.getElementById("passwordstrengthstatus").innerHTML = "weak";
document.getElementById("passwordstrengthstatus").style.setProperty('background-color', 'red', 'important');
}
}else{
document.getElementById("passwordstrengthstatus").style.display = "none";
}
}
As you can see, it will check if the password is not empty and it's length is more than 12 characters, then go ahead and check for e.match(format1).
But the problem is, when I enter those characters as well, it will not return this condition as true and therefore the message strong does not appear and still shows normal message on screen.
So what's going wrong with this?
How can I solve this problem and properly check if the string contains the written symbols or not?
If you just want to check for the presence of at least one symbol character, then remove the ^ and $ anchors and just use:
var format1 = /[!##$%^&*()_+\=\[\]{};':"\\|,.<>\/?-]/;
Note that the hyphen has been moved to the end of the character class. If you want to stick with your original pattern and match the entire password, then modify to this:
var format1 = /^.*[!##$%^&*()_+\=\[\]{};':"\\|,.<>\/?-].*$/;
Your current regex matches only if the password contains nothing but special characters. try adding a-zA-Z0-9 inside too
^[a-zA-Z0-9!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*$
Related
I'm trying to make a regex to match atleast two special characters,
for a password strength checker. I now have this in Javascript:
if (password.match(/([^A-Za-z0-9]{2,})/)) {
//Add strength
}
But this checks that atleast two special characters that needs to be after each other. How can I make it, so that it will also check if it's not after each other?
Example:
_aaa!* //Match
a!a_a* //Also match
One way to do it:
var password = 'a!a_a*';
var matches = password.match(/([^A-Za-z0-9])/g);
if (matches && matches.length >= 2) {
console.log('Good');
} else {
console.log('Bad');
}
console.log(matches);
You could use replace for this:
var password = 'a!a_a*';
var specialChars = password.replace(/[A-Za-z0-9]/g, '');
console.log(password, specialChars.length > 1 ? 'OK' : 'Too few special chars');
^(.*?[\*\& list all the special characters you want to allow here prefixed by \]){2,}.*$
You can test it here: https://regex101.com/
I need to validate a text box which i am using for search the content which comes from database.Need to restrict special characters at starting but allow after a word.And space also.
Ex: Must allow
java/j2ee
java&servlets
But Not
#java
$java
(space)java
$("#keyvalue").keypress(function (e) {
var regex = new RegExp("^[a-z0-9][a-z0-9_ .-]*$");
var regex1 =new RegExp("[,%_$]");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)){
$("#errormess").html("Please select valid input").show();
}
if(regex1.test(key)) {
e.preventDefault();
} else {
$("#errormess").html("");
}
});
Try something like this
function isValid(){
return !/[#$\s\/&]/g.test(yourString.indexOf(0));
// Returns true if special char not exists at first position
}
You can add more special characters in [#$\s\/&]
Check this snippet
var textbox = document.getElementById('textbox');
var pattern = /^([a-zA-Z0-9]+)([a-zA-Z0-9!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?\s]+)$/;
if(!pattern.test(textbox.value)){
console.log('Not allowed!');
}
or this one, having less complex regex
var textbox = document.getElementById('textbox');
var pattern = /^([a-zA-Z0-9].*)$/;
if(!pattern.test(textbox.value)){
console.log('Not allowed!');
}
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 a wrote one js program so that it will accept the user input from a textfield and then it the program automatically make that user input in to the screen like a status in fb.
in that if i gave that input and when it is displaying the next line sentence is appended to the before sentence.
how can i check that one and correct that mistake?
Thanks in advance.
In a very simple way, this problem can be solved using the indexOf method.
var text = textarea.innerHTML;
if(text.indexOf('\n') !== -1) {
// the text contains a new line
}
The indexOf method returns the index of the expression or -1 if it isn't found.
var text = $("#theTextArea").val();
var match = /.*\r|.*\n/.exec(text);
if (match) {
// Found .. the text area has a sentence already.
}
Check out this fiddle
var x = "Some text\n here";
var patt1 = /\n/;
alert(x);
if(x.search(patt1) > 0)
alert("New line character present");
else
alert("New line character not present");
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