I am trying to make a function that checks for special characters such as !##$%^&*~ when I input a password. I've been using regular expressions to check for everything else, but does anyone know how I can make it so the function checks the password for at least one of these special characters?
Here's what I have:
function validateEmail(email)
{
var emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,3}$/;
return emailPattern.test(email);
}
function validatePassword(password)
{
var passwordPattern = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z])./;
return passwordPattern.test(password)
}
function validate()
{
var email = user.email.value;
if(validateEmail(user.email.value))
user.validEmail.value = "OK";
else
user.validEmail.value = "X";
if(validatePassword(user.password.value))
user.validPassword.value = "OK";
else
user.validPassword.value = "X";
}
You can match any non-(letters, digits, and underscores) characters with \W.
So to check the password if has any special character you can just simply use:
if (password.match(/\W/)) {
alert('you have at least one special character');
}
to use it in your function you can replace the whole regex with:
var passwordPattern = /^[\w\W]*\W[\w\W]*$/;
that will return true if the string has at least one special character.
Related
I'm trying to create a function to check if a field is valid based on a set of characters and, if not, output which ones are not allowed. Don't know if it is the best approach, but basically instead of telling the user which ones he can use, I want to tell which ones he can't.
function allowedString(field){
var validCharacters = new RegExp('^[a-zA-Z0-9áéíóúÁÉÍÓÚñÑ_-¿?¡!.,;:$() ]*$');
if(!validCharacters.test(field.val())){
var invalid = ?;
return "Invalid characters: "+invalid;
}
}
Using your character set in your regex, you can remove all those characters from the string and resultant will be the non-allowed characters. Try this JS codes,
function allowedString(s){
var validCharacters = new RegExp('^[a-zA-Z0-9áéíóúÁÉÍÓÚñÑ_-¿?¡!.,;:$() ]*$');
if(!validCharacters.test(s)){
var invalid = s.replace(/[a-zA-Z0-9áéíóúÁÉÍÓÚñÑ_-¿?¡!.,;:$() ]*/g,'');
return "Invalid characters: "+invalid;
} else {
return "All characters are valid"; // return any message you want
}
}
console.log(allowedString('aa##bb##'));
console.log(allowedString('abc'));
console.log(allowedString('aa##bb##~~^^'));
And change your field parameter in function back to your original code.
You can split the string and deal with it as with an array (not sure about the performance, though).
function allowedString(field){
const validCharacters = new RegExp('^[a-zA-Z0-9áéíóúÁÉÍÓÚñÑ_-¿?¡!.,;:$() ]*$');
const disallowed = field.val().split('').filter(x => !validCharacters.test(x));
if (disallowed.length) {
return disallowed.join('');
}
}
I'd reverse the test: Is there an invalid character within the string?
Take care you have to escape the dash in a character class except in first and last position.
function allowedString(field){
var invalidCharacters =/([^a-zA-Z0-9áéíóúÁÉÍÓÚñÑ_\-¿?¡!.,;:$() ])/;
invalid = invalidCharacters.exec(field);
if (invalid != null) {
return "Invalid characters: "+invalid[1];
} else {
return "OK";
}
}
console.log(allowedString('abc'));
console.log(allowedString('abc#def'));
console.log(allowedString('abc§def'));
I am new to javaScript and the problem I am facing is that I have to match the # symbol and make sure it is allowed only once in a string. To do so I have written the following regex.
var regexpat=/[#]{1}/;
if(regexpat.test(valu))
testresults = true;
else
{
alert("Please input a valid email address!");
testresults = false;
}
My regex is working for the following input value: abcd#abc#abc.com. However, if I provide the input value as "abcd#"#abc.com it is not throwing the alert error message.
How can I change my regex so that it will work for "abcd#"#abc.com?
Your regexp just tests whether there's a single # in the string, it doesn't reject more than one. Use:
var regexppat = /^[^#]+#[^#]+$/;
This matches an # that's surrounded by characters that aren't #.
var valu;
var regexpat = /^[^#]+#[^#]+$/;
while (valu = prompt("Enter email")) {
if (regexpat.test(valu))
console.log(valu + " is valid");
else {
console.log(valu + " is invalid");
}
}
The easy way could also be to use the split("#") for this:
var value = 'abcd##';
if(value.split("#").length === 2){
testresults = true;
}else{
alert("Please input a valid email address!");
testresults = false;
}
Just split your string with # and since you require only one occurrence of # there must be an array of length 2 so you can compare the array with length 2. If the array length is greater than 2 then there are more than one occurrence of #
E-Mail regex is much more, than just the occurence of just one # character. This is the email-regex specified in the W3C Spec (e.g. used for <input type="email">):
/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/
I have created a java script function, it should validate the input character that should contain 10 characters and can contain alphanumeric characters, but this function does not work, please help me
function ValidateNIC(id)
{
var letters = /^[0-9a-zA-Z ]+$/;
while(id.value.length==10)
if(id.value.match(letters))
{
return true;
}
else
{
alert('NIC must have alphanumeric characters only or should contain 10 charaters');
id.focus();
return false;
}
}
With your code as it stands, if the length is not 10, then nothing else happens. A better approach might be:
if ((id.value.length == 10) && id.value.match(letters)) {
return true;
}
alert("NIC must ...");
id.focus();
return false;
You can put all the conditions for validation in Regex like ^[a-zA-Z0-9]{10}$. Note that additional {10} in the regex pattern string for creating a match only when the length is 10 exactly.
Then you can make use of the Regex Object test method, which test the regex pattern against a string and returns true if the match is successful and false otherwise.
Complete modified snippet below with positive and negative test cases.
function ValidateNIC(id){
var aphaPattern10 = /^[a-zA-Z0-9]{10}$/g;
var result = aphaPattern10.test(id.value);
if(!result){
alert('NIC must have alphanumeric characters only or should contain 10 charaters');
//id.focus();
}
return result;
}
var testObjPass = { value : "012345678a"}
console.log(ValidateNIC(testObjPass));
var testObjFail = { value : "012345678a21312"}
console.log(ValidateNIC(testObjFail));
The following code checks the following
NIC must have alphanumeric characters only or should contain 10 charaters.
So if it is only 10 characters then it will not alert else, it will test the regex. Considering id is an object with key value
function ValidateNIC(id)
{
var letters = /^[0-9a-zA-Z ]+$/;
if(id.value.length!==10){
if(id.value.match(letters))
{
return true;
}
else
{
alert('NIC must have alphanumeric characters only or should contain 10 charaters');
id.focus();
return false;
}
}
}
I try to input the following value "f+11111111111", and my code doesn't display error message. I tried to remove regex2 condition, and then it worked. But how come? It's an AND condition, why does it act like it's an OR operator?
function validatePhone()
{
var phone = document.getElementById("phone").value;
var regex1 =/^[\+\d][\s(\-\d][\s()\-\d]{8,}/g;
var regex2 = /\D*(\d\D*){11}/g;
if (!phone.match(regex1) && !phone.match(regex2)) {
producePrompt("Error", "comment_phone_prompt");
return false;
}
}
function producePrompt(message, promptLocation)
{
document.getElementById(promptLocation).innerHTML = message;
}
Your second regular expression /\D*(\d\D*){11}/g matches the given string f+11111111111 and therefore the whole condition evaluates to false. You can visualise your regular expressions using regexper.com.
I'm not sure what you're trying to do but mind that even this string is matched by the second regex: 'f+1dsadsadasda123131231dsdadai-094i-)#)#(#)_(#_!' Is this what you want?
Second regex matches everything. Single regex is enough.
function validatePhone() {
var phone = document.getElementById("phone").value;
var regex1 = /^(\+\d)?(\(|-)?\d{3}(\)|-)?\d{3}-?\d{4}$/;
//match +1-800-123-45678, (555)123-4567, and so on
if (!regex1.test(phone)){
producePrompt("Error", "comment_phone_prompt");
return false;
}
return true;//both sides should return
}
I have JavaScript code to check if special characters are in a string. The code works fine in Firefox, but not in Chrome. In Chrome, even if the string does not contain special characters, it says it contains special characters.
var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";
for (var i = 0; i < chkfile.value.length; i++)
{
if (iChars.indexOf(chkfile.value.charAt(i)) != -1)
{
alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
return false;
}
}
Suppose I want to upload a file desktop.zip from any Linux/Windows machine.
The value of chkfile.value is desktop.zip in Firefox, but in Chrome the value of chkfile.value is c://fakepath/desktop.zip. How do I get rid of c://fakepath/ from chkfile.value?
You can test a string using this regular expression:
function isValid(str){
return !/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}
Try This one.
function containsSpecialCharacters(str){
var regex = /[ !##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/g;
return regex.test(str);
}
Directly from the w3schools website:
var str = "The best things in life are free";
var patt = new RegExp("e");
var res = patt.test(str);
To combine their example with a regular expression, you could do the following:
function checkUserName() {
var username = document.getElementsByName("username").value;
var pattern = new RegExp(/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/); //unacceptable chars
if (pattern.test(username)) {
alert("Please only use standard alphanumerics");
return false;
}
return true; //good user input
}
Did you write return true somewhere? You should have written it, otherwise function returns nothing and program may think that it's false, too.
function isValid(str) {
var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";
for (var i = 0; i < str.length; i++) {
if (iChars.indexOf(str.charAt(i)) != -1) {
alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
return false;
}
}
return true;
}
I tried this in my chrome console and it worked well.
You could also do it this way.
specialRegex = /[^A-Z a-z0-9]/
specialRegex.test('test!') // evaluates to true
Because if its not a capital letter, lowercase letter, number, or space, it could only be a special character
If you don't want to include any special character, then try this much simple way for checking special characters using RegExp \W Metacharacter.
var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";
if(!(iChars.match(/\W/g)) == "") {
alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
return false;
}