Home > Software design >  How to check if a string contains at least one letter in JavaScript?
How to check if a string contains at least one letter in JavaScript?

Time:11-03

I am on validation work. this is my code

if (pwd.match(/[A-Za-z]/)) {
      $("#pwd-complexity-letter").html(good); 
      console.log("pwd complexity  invoked");
}

but this code has checked every string that I am passing through 'pwd'. For example, if I pass numbers or special char code become invoked and satisfying my input has at least one letter. how can I solve this please help. the problem is still on the small letter [a-z] checking. Capital letter only satisfy capital inputs. but the small letter has passed every string.

CodePudding user response:

For this you can use javascript regexp

var regexp = /^[a-z] $/i;
if (regexp.test(pwd)) {
  $("#pwd-complexity-letter").html(good); 
  console.log("pwd complexity  invoked");
}

CodePudding user response:

You can use regexp for it:

[a-z] will match any letter from a to z while /i will tell the regex to be case insensitive.

if (isPasswordValid("a1235@")) {
  console.log("Password valid")
} else {
  console.log("Password invalid")
};


function isPasswordValid(psw) {
  let regex = /^[a-z]/i
  return regex.test(psw) // you test if the passed string match the regex, if it does the function will return true else false.
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

You can use a function like isPasswordValid and pass your psw value in it to check if it's valid or not

  • Related