I have some JQuery form validation where im checking the length of the username is not long for the database but it seems to be returning true eveytime.
Am I missing something?
HTML
<form name="contact" method"post" action="">
<fieldset>
<label for="username" id="username_label" class="form_label">Username</label>
<input type="text" name="username" id="username" size="30" value="" class="text-input" />
<label class="error" for="username" id="username_error">This field is required. </label>
<label class="error" for="username" id="username_length">Your Username should be less than 30 characters.</label>
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</fieldset>
</form>
JavaScript
$(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form here
$('.error').hide();
var username_length = $("input#username").val().length;
if (username_length < 30) {
$("label#username_length").show();
$("input#username").focus();
return false;
}
}
You can use JQuery Validator plugin to do this;
just need change your html for something like this;
<label for="username">User Name:</label>
<input type="text" name="username" id="username" value="..." />
using this approach you don't need define this multiple tags labels with differents ids (username_error, username_length) to handle every single constraint message,and don't need worry about hide these tags, the jquery plugin will handle this for you and put the appropriate message in lable rotule with 'username' for you. And fell free to customize this messages.
your js will be like these;
$("form[name=contact]").validate({
//...
rules: {
username: {
required: true,
maxlength: 30
}
//...
});
your code will be more clean, See API documetation for more information, http://docs.jquery.com/Plugins/Validation
I have some JQuery form validation where im checking the length of the username is not long for the database but it seems to be returning true eveytime.
You are checking if unsername is shorter then 30, not longer!
if (username_length < 30) {// !!!
note:
$("input#username")
=> $('#username')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With