I’m trying to get a value of several URL input and if value of URL isn’t not valid, I just want to animate input element and stop everything.
Is there any way to do it?
JavaScript
x
24
24
1
$('button').click(function(e){
2
var linkarr = [];
3
var $input = $('.default');
4
var isValidUrl = /[0-9a-z_-]+.[0-9a-z_-][0-9a-z]/; // URLvalid check
5
6
$input.each(function() {
7
var inputVal = $(this).val();
8
if(!isValidUrl.test(inputVal)) {
9
$(this).parent().animateCss('shake');
10
// if input is not valid, I want to stop the code here.
11
}
12
if(inputVal) linkarr.push(inputVal);
13
});
14
15
e.preventDefault();
16
$.ajax({
17
url: '/api/compress',
18
type: 'POST',
19
dataType: 'JSON',
20
data: {url: linkarr},
21
success: function(data){ something
22
});
23
});
24
Advertisement
Answer
You need to let outside of your each loop know the condition of the contents.
JavaScript
1
33
33
1
$('button').click(function(e){
2
var linkarr = [];
3
var $input = $('.default');
4
var isValidUrl = /[0-9a-z_-]+.[0-9a-z_-][0-9a-z]/; // URLvalid check
5
var blnIsValid = true;
6
7
$input.each(function() {
8
var inputVal = $(this).val();
9
if(!isValidUrl.test(inputVal)) {
10
$(this).parent().animateCss('shake');
11
// if input is not valid, I want to stop the code here.
12
// Input isn't valid so stop the code
13
blnIsValid = false;
14
return false; // Alternatively don't stop so that any other invalid inputs are marked
15
}
16
17
if(inputVal) linkarr.push(inputVal);
18
});
19
20
e.preventDefault();
21
22
// Check to make sure input is valid before making ajax call
23
if (blnIsValid) {
24
$.ajax({
25
url: '/api/compress',
26
type: 'POST',
27
dataType: 'JSON',
28
data: {url: linkarr},
29
success: function(data){ something
30
});
31
}
32
});
33