Reputation: 709
Currently, I'm using the following code but it doesn't seem to work. I would like to throw an error if a user fails to enter an "@" symbol in an input field. Please bear with me. Thanks
My following code is:
var emailaddressVal = $("input[name='emailAddress']").val().split('@').slice(1)[0].trim();
if(emailaddressVal .match(/@/) !== null) {
alert('An @ symbol was not entered');
}
Upvotes: 0
Views: 521
Reputation: 2323
Looks like you're doing a lot more work than you need to. Your split()
call searches for the bad character, so you could stop there and see if the string was split or not. But that's not a very clear way of expressing your intent.
If you're looking for a specific character, you don't need a regex.
Why not just
if ( $("input[name='emailAddress']").val().indexOf('@') > -1 ) {
/* we found an '@' character; handle as you like */
} else {
/* NOT FOUND, handle as appropriate */
alert("Missing a required '@' character");
}
indexOf
returns a non-negative value if it finds the string. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
Upvotes: 3
Reputation: 85528
Whats wrong with indexOf
? It does not always have to be so complicated :
<input type="text" id="test">
document.getElementById('test').onkeyup = function() {
if (this.value.indexOf('@')>-1) {
alert('error');
}
}
or jQuery
$("#test").on('keyup', function() {
if ($(this).val().indexOf('@')>-1) {
alert('error');
}
});
demo -> http://jsfiddle.net/t49xdx56/
Upvotes: 1