Find your people. Pick a challenge. Ship something real. The CreatorCon Hackathon is coming to the Community Pavilion for one epic night. Every skill level, every role welcome. Join us on May 5th and learn more here.

validation regex

Buddy 1
Tera Contributor

Hi,

I have a field validation which can allow alphanumeric and special characters with 10 digit . But if the value entered is only alphabet or only special characters , it should not allow.

for eg:

the validation can be like --> 123$nj-jka

the validation should not be like --> asdfghnjkr 

the validation should not be like --> @#$%^&*()_

 

Can anyone help?

Thanks in advance!

4 REPLIES 4

Teja11
Giga Guru

Hi @Buddy 1 ,

 

use the below code

 

function validateField(value) {
  // Check if value is 10 characters long
  if (value.length !== 10) {
    return false;
  }

  // Check if value is alphanumeric or contains special characters
  var regex = /^(?=.*[a-zA-Z])(?=.*[@$!%*#?&])[a-zA-Z\d@$!%*#?&]+$/;
  if (!regex.test(value)) {
    return false;
  }

  // Check if value is only alphabetical or only special characters
  var letters = /^[A-Za-z]+$/;
  var specialCharacters = /^[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*$/;
  if (letters.test(value) || specialCharacters.test(value)) {
    return false;
  }

  return true;
}

 

Regards,

Teja

 

If my answer has helped with your question, please mark my answer as accepted solution and give a thumb up.

Buddy 1
Tera Contributor

Hi @Teja11 ,

Thanks for the code, Is it possible to make the same using validation regex . 

Can you help me with the regular expression .

 

Thanks in advance!

sure here's the one line regular expression

 

/^(?=.*[a-zA-Z])(?=.*[@$!%*#?&])[a-zA-Z\d@$!%*#?&]{10}(?<![a-zA-Z])(?<![@$!%*#?&])$/

Example:

 

var regex = /^(?=.*[a-zA-Z])(?=.*[@$!%*#?&])[a-zA-Z\d@$!%*#?&]{10}(?<![a-zA-Z])(?<![@$!%*#?&])$/;
var inputValue = "123$nj-jka";

if (regex.test(inputValue)) {
  // Input value is valid
} else {
  // Input value is invalid
}

 

Regards,

Teja

 

If my answer has helped with your question, please mark my answer as accepted solution and give a thumb up.