javascript - How can you check if an input (email) field contains a special character using JQuery -
currently, i'm using following code doesn't seem work. throw error if user fails enter "@" symbol in input field. please bear me. thanks
my following code is:
var emailaddressval = $("input[name='emailaddress']").val().split('@').slice(1)[0].trim(); if(emailaddressval .match(/@/) !== null) { alert('an @ symbol not entered'); }
looks you're doing lot more work need to. split()
call searches bad character, stop there , see if string split or not. that's not clear way of expressing intent.
if you're looking specific character, don't need regex.
why not
if ( $("input[name='emailaddress']").val().indexof('@') > -1 ) { /* found '@' character; handle */ } else { /* not found, handle appropriate */ alert("missing required '@' character"); }
indexof
returns non-negative value if finds string. see https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/string/indexof
Comments
Post a Comment