Reputation: 329
I want to validate an input field input or textarea with a COMPULSIVE Alphanumeric requirement
Conditions -
It should compulsorily have Numbers as well as Alphabets
It should allow only these Special Characters , / - ( ) # . (namely * Space, Comma, Forward Slash, Hyphen, Hash, Round Brackets, Dot*)
It should be of minimum length (assume 10). The length here refers to the combined length of all inputs.
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
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
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,}$
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