I want my email form filed to be validated by jQuery.
if user typed val() matches any values in array, i want to run some function before submitting.
ex. if I type
abc.com
is not in array. so OK.
bbb.net
is in array. so NG.
username@ccc.co.uk
part of string is in array. so NG.
blah@aaa.ne.
i do not care... let PHP decide if its valid email. so javascriptly OK.
html:
<form action="./" method="post" id="test">
email address: <input type="text" id="mail">
<input type="submit" val="SUBMIT " id="subm">
</form>
javascript:
var arr = [
'aaa.ne.jp', 'bbb.net', 'ccc.co.uk', 'ddd.co.kr'
];
$('#test').on('submit', function() {
var _value = $('#mail').val();
if( $.inArray(_value, arr) > 0 || _value == '') {
console.log(_value + ' cant be accepted');
return false;
} else {
console.log(_value + ' is GO!');
return false;//do not submit just for the sake of example.
}
});
i used jquery's inArray()
method, but somehow ,for example, username@ccc.co.uk
gets through the validation even though ccc.co.uk
is in array.
any solution will be appreciated. thanx.
Try splitting the email
and compare the latter part after @
var arr = [
'aaa.ne.jp', 'bbb.net', 'ccc.co.uk', 'ddd.co.kr'];
$('#test').on('submit', function () {
var _value = $('#mail').val();
if (_value !== '' && _value.indexOf('@') > -1) {
var parts = _value.split('@');
if ($.inArray(parts[1], arr) > 0 || _value == '') {
console.log(_value + ' cant be accepted');
return false;
} else {
console.log(_value + ' is GO!');
return false; //do not submit just for the sake of example.
}
} else {
console.log(_value + ' cant be accepted');
return false;
}
});
The email value you are comparing has more characters that what is needed for the inArray() method to work. It is not a direct comparison. You could do this. It gets everything after the '@' to compare in $.inArray.
$('#test').on('submit', function() {
var _value = $('#mail').val();
var _value2 = _value.split("@").pop();
if( $.inArray(_value2, arr) > 0 || _value2 == '') {
console.log(_value + ' cant be accepted');
return false;
} else {
console.log(_value + ' is GO!');
return false;//do not submit just for the sake of example.
}
});
You can use grep
var arr = [
'aaa.ne.jp', 'bbb.net', 'ccc.co.uk', 'ddd.co.kr'];
$('#test').on('submit', function () {
var _value = $('#mail').val(),
_matches = $.grep(arr, function (val, i) {
return _value.indexOf(val) != -1
});
if (_matches.length > 0) {
//contains something
} else {
console.log(_value + ' cant be accepted');
return false;
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.