Reputation: 63
I am trying to increase security on Email/Password input fields using regular expressions but I am having bad time because I cannot find what I am doing wrong. So basically I'm creating 2 variables where I'm storing my Regex pattern and after that I want to use jquery to catch the submit button and when .on('click') if there is added correct information by users to redirect them to next page for example. I have been testing my regular expression and they are matching my requirements - they are returning true for Email/Password after testing with .test(). Here is my code example of what I am trying to build:
var userValidation = /^[\w-]+@[\w-]+\.[A-Za-z_-]{2,4}$/;
var passValidation = /((?=.*d)(?=.*[a-z])(?=.*[A-Z]).{8,15})/gm;
console.log(userValidation.test('[email protected]')); // testing
console.log(passValidation.test('12345678Kksad')); // testing
Actual code which I am trying to run
$('.button').on('click', function(){
if ($('#user') === userValidation && $('#pass') === passValidation){
window.location.replace("http://stackoverflow.com");
}else{
console.log('not working properly');
}
})
Every time when I enter email and password in both input fields it returning the else statement does not matter if the information is correct or not according my regular expressions.
Upvotes: 0
Views: 644
Reputation: 10228
There is several issue in your code.
Here is a complete example.
CSS :
<form id="form" action="/validate" method="POST">
<input type="text" name="email"/>
<input type="password" name="password">
<button type="submit" >Submit</button>
</form>
JS :
var emailRegex = /^[\w-]+@[\w-]+\.[A-Za-z_-]{2,4}$/;
var passRegex = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[\da-zA-Z]{8,}$/;
$('#form').submit(function(event) {
event.prevendDefault();
// get email and password value
var email = $(this).find('input[name=email]').val();
var password = $(this).find('input[name=password]').val();
// validate email and password
if (emailRegex.test(email) && passRegex.test(password)){
window.location.replace("http://stackoverflow.com");
} else {
console.log('not working properly');
}
});
Upvotes: 3
Reputation: 56
Alternatively, you could make a minor change to your existing event handler function to match the input field values with your regular expressions;
$('.button').on("click", function () {
if ($('#user').val().match(userValidation) && $('#pass').val().match(passValidation)) {
window.location.replace("http://stackoverflow.com");
} else {
console.log('not working properly');
}
});
Upvotes: 1