[jQuery] Leeres Passwortfeld im Formular ohne Error message

od-boy

Ensign
Registriert
Nov. 2007
Beiträge
224
Hallo,

folgender Code:
http://jsfiddle.net/antishok/ZCVCL/14/ oder unten direkt:
Code:
<!DOCTYPE HTML>
<html>
<head>
<title>jQuery: Advanced Techniques - Practical</title>
<style>
	body {
	    width: 500px;
	}
	.my-row {
	    width: 100%;
	    padding: 5px;
	    border-bottom: 1px solid #000;
	}
	label {
	    margin-right: 5px;
	}
	.label-left {
	    text-align: right;
	}
	.label-right {
	    text-align: left;
	}
	.error {
	    color: #cc0000;
	}
	/* The Overlay: */
	.overlay {
	    /* General properties: */
	    /* - Hidden when the page is first displayed */
	    display: none;
	    /* - Displayed on top of the other page elements */
	    z-index: 10000;
	    top: 0.5px;
	    /* Appearance: */
	    background-color: #F778A1;
	    padding: 0.5px;
	    border: 1px solid #000000;
		}
	/* The Close Button: */
	.overlay-close {
	    /* Button image: */
	    background-image: url(close.png);
	    background-repeat:no-repeat;
	    /* Location: */
	    position: absolute;
	    right: -5px;
	    top: 2px;
	    /* Mouse cursor: */
	    cursor: pointer;
	    /* Size: */
	    height: 35px;
	    width: 35px;
		}
			
</style>

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
  $(document).ready(function() {
    
    function myValidateEMailAddress(email_address) {
      var email_pattern = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
      return email_pattern.test(email_address);
    }
    
    function checkPassword(password) {
	var my_pwd_pattern = /^(?=.*[a-zA-Z].*[a-zA-Z])(?=.*\d.*\d)[a-zA-Z0-9_]{6,20}$/;
	return my_pwd_pattern.test(password);
	}
	
    $(document).ready(function() {    
      $('#my_form').submit(function(e) {
        
        var my_errors = false;
        $('.my-row > .error').remove();
        $('#my_submission').empty();
        $(':text, textarea').each(function() {
          $(this).val($.trim($(this).val()));
          if ($(this).val() == '') {
            $(this).parent().append('<div class="error">Please provide a value</div>');
            my_errors = true;
          }
        });
        if ($('#email').val() != '') {
          if (!myValidateEMailAddress($('#email').val())) {
            $('#email').parent().append('<div class="error">Please type in a correct e-mail address</div>');
            my_errors = true;
          }
        }

		if ($('#password').val() != '') {
          if (!checkPassword($('#password').val())) {
            $('#password').parent().append('<div class="error">Please type in a correct password</div>');
            my_errors = true;
          }
        }
        if ($(':radio[name="form_of_address"]:checked').length == 0) {
          $(':radio[name="form_of_address"]:first').parent().after('<div class="error">Please select one item</div>');
          my_errors = true;
        }
        if ($(':radio[name="sex"]:checked').length == 0) {
          $(':radio[name="sex"]:first').parent().after('<div class="error">Please select one item</div>');
          my_errors = true;
        }
        if ($('.interests:checked').length == 0) {
          $('.interests:first').parent().after('<div class="error">Please select at least one item</div>');
          my_errors = true;
        }
        if ($('#newsletter option:selected').val() == '') {
          $('#newsletter').parent().append('<div class="error">Please select one item</div>');
          my_errors = true;
        }
        if (my_errors) {
          return false;
        }
        else {
          if(confirm('Do you confirm your entries?')) { 
            e.preventDefault();
            $('body').append($(this).find('.my-row').clone());
            $('#overlay1').hide();
              
            var my_submission_array = $('#my_form').serializeArray();
            if (my_submission_array.length > 0) {
              $('.my-row').hide();
                $('#my_submission').html('<h2>Submitted Elements</h2><ul></ul>');
                $.each(my_submission_array, function(i, item) {
                    $('#my_submission > ul').append('<li>' + item.name + ': ' + item.value + '</li>\n');
                });
                
            }
          } else { return false;  }
        }      
      });
    });
    $(document).ready(function() {
      $('a.overlay-link').click(function() {
        var my_overlay_id = $($(this).attr('rel'));
        my_overlay_id.prepend('<div class="overlay-close"></div>').show();
        $(document).on('click', '.overlay-close', function() {
          my_overlay_id.hide();
        });
      });
    });
  });
</script> 

</head>
<body>
    	<h2><u>jQuery: Advanced Techniques - Practical</u></h2>

    	<h3>Task 3</h3>

    <br>
    <div id="overlay1" class="overlay">
        	<h2>Fill out this form!</h2>

        <form name="my_form" id="my_form" action="" method="post">
            <div class="my-row">
                <fieldset>
                    <legend><b>Form of address:</b>

                    </legend>
                    <input type="radio" name="form_of_address" id="group1" value="Mr">
                    <label for="group1" class="label-right">Mr</label>
                    <input type="radio" name="form_of_address" id="group2" value="Ms">
                    <label for="group2" class="label-right">Ms</label>
                </fieldset>
            </div>
            <div class="my-row">
                <fieldset>
                    <legend><b>Sex:</b>

                    </legend>
                    <input type="radio" name="sex" id="group1" value="Male">
                    <label for="group1" class="label-right">Male</label>
                    <input type="radio" name="sex" id="group2" value="Female">
                    <label for="group2" class="label-right">Female</label>
                </fieldset>
            </div>
            <div class="my-row">
                <label for="last_name" class="label-left"><b>Last Name: </b>

                </label>
                <input type="text" name="last_name" id="last_name">
            </div>
            <div class="my-row">
                <label for="first_name" class="label-left"><b>First Name: </b>

                </label>
                <input type="text" name="first_name" id="first_name">
            </div>
            <div class="my-row">
                <label for="email" class="label-left"><b>E-Mail: </b>

                </label>
                <input type="text" name="email" id="email">
            </div>
            <div class="my-row">
                <label for="password" class="label-left"><b>Password: </b>

                </label>
                <input type="password" name="password" id="password">
            </div>
            <div class="my-row">
                <fieldset>
                    <legend><b>What are your interests?</b>

                    </legend>
                    <input type="checkbox" name="interests" class="interests" id="interest1" value="sleeping">
                    <label for="interest1" class="label-right">Sleeping</label>
                    <input type="checkbox" name="interests" class="interests" id="interest2" value="lazy">
                    <label for="interest2" class="label-right">Being lazy</label>
                    <input type="checkbox" name="interests" class="interests" id="interest3" value="eating">
                    <label for="interest3" class="label-right">Eating</label>
                    <input type="checkbox" name="interests" class="interests" id="interest4" value="movies">
                    <label for="interest4" class="label-right">Watching movies</label>
                    <input type="checkbox" name="interests" class="interests" id="interest5" value="music">
                    <label for="interest5" class="label-right">Listening to music</label>
                </fieldset>
            </div>
            <div class="my-row">
                <label for="newsletter" class="label-left"><b>Do you want to subscribe to a newsletter?</b>

                </label>
                <select name="newsletter" id="newsletter">
                    <option value="">Make your choice</option>
                    <option value="yes">Yes</option>
                    <option value="no">No</option>
                </select>
            </div>
            <div class="my-row">
                <label for="comments" class="label-left"><b>Any comments?</b>

                </label>
                <textarea name="comments" id="comments" cols="40" rows="3"></textarea>
            </div>
            <div class="my-row">
                <input type="submit" name="submit" id="submit" value="Submit">
            </div>
        </form>
    </div>	<a href="#" rel="#overlay1" class="overlay-link">Click here to open the form in an overlay</a>
            <div id="my_submission"></div>
</body>
</html>

Wenn man das Passwortfeld leer lässt, kommt keine Meldung raus, wie es bei den anderen Feldern der Fall ist.
Wie im Code ersichtlich habe ich das doch aber auch definiert (Zeile 66-69 und 91-95)
Was habe ich da falsch?

Grüße,
od-boy
 
Bissl unübersichtlich.

Als blur() Funktion funktioniert dein Code. Problem liegt wohl woanders.

Code:
function checkPassword(password) {
var my_pwd_pattern = /^(?=.*[a-zA-Z].*[a-zA-Z])(?=.*\d.*\d)[a-zA-Z0-9_]{6,20}$/;
return my_pwd_pattern.test(password);
}



$('#password').blur(function(){ 
if ($('#password').val() != '') {
if (!checkPassword($('#password').val())) {
$('#password').parent().append('<div class="error">Please type in a correct password</div>');
my_errors = true;
}
}
});
 
Zuletzt bearbeitet:
im if Zweig: $('#password').val().length < 1

BTW: Solche spielerischen Sachen wie das aufklappen behindern beim Debuggen doch den Workflow, also erst zum Schluß...

€dit: Ich weis das ist Übungscode, aber für neue Browser gibts für input Felder das required Attribut.
 
Zuletzt bearbeitet:
@palace4d,

$('#password').val().length < 1 funktioniert wunderbar!
Nur, das (oder der?) pattern, also
var my_pwd_pattern = /^(?=.*[a-zA-Z].*[a-zA-Z])(?=.*\d.*\d)[a-zA-Z0-9_]{6,20}$/;
wird anscheinend dann nicht mehr "verwendet"...
 
Code:
<div class="my-row">
    <label for="password" class="label-left"><b>Password: </b></label>
    <input type="password" name="password" id="password">
</div>


<script>


var errors = [];
errors.push('<div id="pw" class="error">Please type in a correct password</div>');

function checkPassword(password) {
    var my_pwd_pattern = /^(?=.*[a-zA-Z].*[a-zA-Z])(?=.*\d.*\d)[a-zA-Z0-9_]{6,20}$/;
    alert(my_pwd_pattern.test(password));
}

 
$('#password').blur(function(){ 
    ($('#password').val().lenght!=0)&&!checkPassword($('#password').val()) ?
    $('#pw').length||($('#password').parent().append(errors[0]),my_errors=true) :
    void 0;
});
</script>

K.A ob deine regex korrekt ist aber obiges Snippet gibt bei einem leeren Feld ein false, bei nicht regexkonformen Input ebenfalls und prüft ob das Errordiv schon existiert anstatt ein weiteres anzuhängen.

Wenn das PW RegExKonform ist müsste ein alert('true') aufpoppen.

Da ich zu faul bin deine RegEx zu interpretieren müsstest du mal ein valides Beispiel anbieten.
 
Zuletzt bearbeitet:
Ich habe es nun wie folgt gelöst:
Code:
      function checkPassword(password) {
          var my_pwd_pattern = /^(?=.*[a-zA-Z].*[a-zA-Z])(?=.*\d.*\d)[a-zA-Z0-9_]{6,20}$/;
          return my_pwd_pattern.test(password);
      }

          if (!checkPassword($('#password').val())) {
              $('#password').parent().append('<div class="error">Please type in a correct password</div>');
              my_errors = true;
          }

Das funktioniert wunderbar.
 
Wenn ein Nutzer 5 mal ein ungültiges Formular abschickt hast du 5 mal die Fehlermeldung pro fehlerhaftem Feld.

Die Fehlermeldungen an sich, inklusive der divs, würde ich in ein array setzen. Ist übersichtlicher.

var errors = [];
// = errors[0]
errors.push('<div id="pw" class="error">Please type in a correct password</div>');
// = errors[1]
errors.push('<div id="ml" class="error">Please type in a correct mail</div>');

Einige deiner Funktionen lassen sich zu einer einzigen zusammenlegen.
 
Zurück
Oben