Alpha
Alpha

Reputation: 329

JS Validation Function to for compulsive Alphanumeric & Special Characters Input Value

I want to validate an input field input or textarea with a COMPULSIVE Alphanumeric requirement

Conditions -

Please keep in mind it is compulsive validation for an address field

The input field shall be set with class name as ".address"

HTML

<input type="text" id="address_1" class="address">
<input type="text" id="address_2" class="address">
<div class="banner-message">

</div>
<div class="match-message">

</div>

jQuery/JS

$(".address").keyup(function()
{

address_1 = $("#address_1").val();
address_2 = $("#address_2").val();

full_address = address_1.concat(address_2);
// alert(address);

ADDRESS_REGEX = /^(?=.\d)(?=.[a-z])[a-z\d,.()&"##\s-]{10,}$/gi;

//$(".match-message").html(ADDRESS_REGEX.test(full_address));
$(".match-message").html(full_address); // Just to check the combined value from all inputs

if(ADDRESS_REGEX.test(full_address)==true)
{
$(".banner-message").html("Your address is perfect!");
}
else
{
$(".banner-message").html("Please input full address");
}


});

Check my JS Fiddle

Upvotes: 0

Views: 450

Answers (2)

Alpha
Alpha

Reputation: 329

The issue was in the usage of g (global) in the regex

Correct

ADDRESS_REGEX = /^(?=.*\d)(?=.*[a-z])[a-z\d,.&"()##\s-]{30,}$/i;

Upvotes: 0

Code Maniac
Code Maniac

Reputation: 37755

You should use test when you want to just test whether it follows the pattern or not instead of match, test returns a boolean value whereas match returns an array of matched values.

You can use this pattern

^(?=.*\d)(?=.*[a-z])[a-z\d,.()#\s-]{10,}$

enter image description here

let addresses = ["hello12312","hellohello","hello-ajd-ajdnajdnasa123","hellohahahahaha-128282()#,.","a 215469874651569847"]

addresses.forEach(address =>{
  let isFine = /^(?=.*\d)(?=.*[a-z])[a-z\d,.()#\s-]{10,}$/i.test(address)
  console.log(address, isFine)
})

Upvotes: 3

Related Questions