Regex requirement to have # symbol only once in a string - javascript

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-]+)*$/

Related

Regex - Output character not valid

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'));

validation function doesn't work

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;
}
}
}

Javascript check for 1 special character and 2 digits

How to create a javascript validation for a password field which must contain at least one special character and at least two digits ?
Exact regular expression that perfect match to your query is below, it is tested ...
^(?=.*?[0-9].*?[0-9])(?=.*[!##$%])[0-9a-zA-Z!##$%]{8,}$
function check(str){
var temp = str;
if(/^[a-zA-Z0-9- ]*$/.test(str) == false && temp.replace(/[^0-9]/g,"").length>1) return true;
return false;
}

Validation to allow space character only when followed by an alphabet

I am trying to validate the textbox which has to allow space character only when followed by any alphabetic character. My code fails when only a space character is inserted. What is the mistake in my code. Suggestions pls..
javascript :
function validate() {
var firstname = document.getElementById("FirstName");
var alpha = /^[a-zA-Z\s-, ]+$/;
if (firstname.value == "") {
alert('Please enter Name');
return false;
}
else if (!firstname.value.match(alpha)) {
alert('Invalid ');
return false;
}
else
{
return true;
}
}
view:
#Html.TextBoxFor(m => m.FirstName, new { #class = "searchbox" })
<button type="submit" onclick="return validate();">Submit</button>
Conditions I applied :
Eg: Arun Chawla - condition success
Eg: _ - condition fails (should not allow space character alone)
try following regex
var alpha = /^[a-zA-Z-,]+(\s{0,1}[a-zA-Z-, ])*$/
First part forces an alphabetic char, and then allows space.
May be using the "test" method like this:
/^[a-zA-Z-,](\s{0,1}[a-zA-Z-, ])*[^\s]$/.test(firstname)
Only returns true when it's valid
Here's a link
I found Akiross's answer to be the best fit for me.
([a-z] ?)+[a-z]
This will allow the space between every character,number and special character(#).
pattern to be followed:
['', [Validators.email,
Validators.pattern('^[[\\\sa-z 0-9._%+-]+#[\\\sa-z0-9.-]+\\.[\\\sa-z]{2,4}]*$')]],
output:
e 2 # 2 g . c o
if(!/^[A-Za-z\s]+$/.test(name)) {
errors['name'] = "Enter a valid name"
}

Checking form for special characters in JavaScript.

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.

Categories

Resources