Link
Link

Reputation: 403

Check form for similar value before submit

Is there anyway to check if a similar value exist in an input box

EX:

<form>
  USER 1
  <input name="user1" value="bla1">
  <input name="pass1" value="ple1">
  <input name="email1" value="[email protected]">

  USER 2
  <input name="user2" value="bla2">
  <input name="pass2" value="ple1">
  <input name="email2" value="[email protected]">

  USER 3
  <input name="user3" value="bla1">
  <input name="pass3" value="pla3">
  <input name="email3" value="[email protected]">

  <button type="submit">
</form>

The verification will trigger when the form is submitted, it will alert the user and add a class to both the input with the similar value. All the input fields starts at blank and the user should input the values. All fields should only be compared to its type USER,PASS, and EMAIL

Upvotes: 1

Views: 710

Answers (1)

SpoonNZ
SpoonNZ

Reputation: 3829

I've put together a wee jsfiddle for you.

Basically it just loops through every element in the form, finds any with similar names, and if they have the same value it marks them both. This is a little inefficient as it compares A with B, then B with A, but still works well.

$('form').submit(function(event) {
    var ok = true,
        $form = $(this),
        $inputs = $(this).find('input')
    $inputs.removeClass('error')
    $inputs.each(function() {
        var $src = $(this)

        //Get the name of the element, and strip off the number
        var name = $(this).attr('name').replace(/[0-9]/g,'')

        //Filter the inputs down to only the ones whose name starts the same
        $inputs.not(this).filter('[name^="' + name + '"]').each(function() {
           if($src.val() == $(this).val()) {
                ok = false
                $(this).addClass('error')
                $src.addClass('error')
            }
        })
    })
    if(!ok) event.preventDefault()
})

Upvotes: 1

Related Questions