yolohoam yolohoam - 2 months ago 8
Javascript Question

How to stop function if input is invalid?

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?

$('button').click(function(e){
var linkarr = [];
var $input = $('.default');
var isValidUrl = /[0-9a-z_-]+\.[0-9a-z_-][0-9a-z]/; // URLvalid check

$input.each(function() {
var inputVal = $(this).val();
if(!isValidUrl.test(inputVal)) {
$(this).parent().animateCss('shake');
// if input is not valid, I want to stop the code here.
}
if(inputVal) linkarr.push(inputVal);
});

e.preventDefault();
$.ajax({
url: '/api/compress',
type: 'POST',
dataType: 'JSON',
data: {url: linkarr},
success: function(data){ something
});
});

Answer

You need to let outside of your each loop know the condition of the contents.

$('button').click(function(e){
  var linkarr = [];
  var $input = $('.default');
  var isValidUrl = /[0-9a-z_-]+\.[0-9a-z_-][0-9a-z]/; // URLvalid check
  var blnIsValid = true;

  $input.each(function() {
    var inputVal = $(this).val();
    if(!isValidUrl.test(inputVal)) {
      $(this).parent().animateCss('shake');
      // if input is not valid, I want to stop the code here.
      // Input isn't valid so stop the code
      blnIsValid = false;
      return false; // Alternatively don't stop so that any other invalid inputs are marked
    } 

    if(inputVal) linkarr.push(inputVal);
  });

  e.preventDefault();

  // Check to make sure input is valid before making ajax call
  if (blnIsValid) {
    $.ajax({
      url: '/api/compress',
      type: 'POST',
      dataType: 'JSON',
      data: {url: linkarr},
      success: function(data){ something
    });
  }
});