bridgemanusa
bridgemanusa

Reputation: 73

Check for string in form field using JS

I have a simple form validator that checks to make for some field values are present and it works great, however we have recently been getting lots of BOT submissions in the form of entering a URL in the "Name" fields. I tried inserting s function to look for "http://" in the first_name field string but the form ignores the check. Ideally I think it might make more sense to check for the "http://" value in any of the form fields just to really stick it back to the bot but am unsure how to call both functions at the same time for each field and stuck just getting it to recognize one.

Here is (most) of the validator itself.

function checkForm( form ){
  function BogusUrl(str) {
      var pattern = new RegExp('^(http?:\\/\\/)?'); // look for URL in string
      if(pattern.form.first_name(str)) {
          alert( 'First Name is Bogus' ); // for testing
      return false;
       }
}
if( isEmpty( form.first_name ) ){
    alert( 'First Name is required field!' );
    return false;
    }
    if( isEmpty( form.last_name ) ){
    alert( 'Last Name is required field!' );
    return false;
    }
return true;
}

Edited for Alex and Manolo suggestions:

function BogusUrl(str) {
var pattern = new RegExp('^https?:\\/\\/'); // look for URL in string
    if(str.match(pattern)) {
    //alert( 'First Name is Bogus' ); // for testing
    return false;
  }
}


function checkForm( form ){
 if( BogusUrl(form.first_name.value.match(pattern))) {
    alert( 'First Name is Bogus' );
    return false;
} 
return true;
}

Upvotes: 1

Views: 676

Answers (2)

Manolo
Manolo

Reputation: 26370

var pattern = new RegExp('^(http?:\\/\\/)?'); // look for URL in string

Here you're checking "htt" and optionally "p". You should do:

var pattern = new RegExp('^(https?:\\/\\/)?'); // look for URL in string

or just:

var pattern = new RegExp('^(http:\\/\\/)?'); // look for URL in string

In your second option, you're not using the str parameter in the function. You should do:

function BogusUrl(str) {
  var pattern = new RegExp('^(https?:\\/\\/)?'); // look for URL in string
  if(str.match(pattern)) {
  alert( 'First Name is Bogus' ); // for testing
  return false;
  }
}

Also, you are testing if the string contains http(s):// or not! ?, so you should delete the interrogant:

function BogusUrl(str) {
  var pattern = new RegExp('^https?:\\/\\/'); // look for URL in string
  if(str.match(pattern)) {
  alert( 'First Name is Bogus' ); // for testing
  return false;
  }
}

Upvotes: 2

Alex
Alex

Reputation: 7374

I think you're missing the match part of that:

if(form.first_name.value.match(pattern))

Upvotes: 2

Related Questions