Reputation: 81
I have a password field and I need to check using javascript if it has the following characters:
! @ # $ % ^ & *
I tried to do it like this, and it's working as expected:
function ValidarPass()
{
var Contrasena = document.getElementById('Clave').value;
if(Contrasena!='' &&
(Contrasena.indexOf('!')>-1||
Contrasena.indexOf('@')>-1||
Contrasena.indexOf('#')>-1||
Contrasena.indexOf('$')>-1||
Contrasena.indexOf('%')>-1||
Contrasena.indexOf('^')>-1||
Contrasena.indexOf('&')>-1||
Contrasena.indexOf('*')>-1))
{
alert("Exito!");
}
else
{
alert("Error!");
}
}
Is there an easier/efficient way to do this?
Upvotes: 0
Views: 317
Reputation: 5397
While both answers here do solve the issue, just for demo I will submit one approach that doesn't use RegEx. Maybe we don't always need to use regular expressions, even for the simplest checks. And the list of characters is pretty short here, one other option could be:
let testString = 'abcd';// the string you are checking
let chars = '!@#$%^&*'.split('');// just a way to write your chars as an array
let isValid = chars.some((c) => testString.includes(c));// check if at least one of the chars is included in your string
Did not really benchmark, but I am hoping it's pretty quick, as the some
method should return as early as it finds a positive match and includes
also.
Maybe you will need some polyfills for some
and includes
methods or replace the arrow function with a regular function depending on what kind of browsers you want to support, this is just to demo an idea.
Upvotes: 0
Reputation: 1014
you can test a string using regex: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
function isValid(str){
return !/[!@#$%^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}
Upvotes: 2
Reputation: 2463
A regex would be a nice one line solution. But it's actually slower than indexOf (like the code you posted). See some information here: https://jsperf.com/regexp-vs-indexof
Regex docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
function isValid(str){
return /[!@#$%^&*(),.?":{}|<>]/g.test(str);
}
Also this site is great for testing regexs https://www.regextester.com/
Upvotes: 0
Reputation: 133
The Regular Expression that you would use to achieve this would be [!@#$%^&*]
This will check for all the special characters that you have listed. For use in a function you can use the matches function like so:
public boolean isSpecialCharacter(String string) {
String pattern = "[!@#$%^&*]";
return string.matches(pattern);
}
Upvotes: 0