Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery form string length validation

Tags:

html

jquery

forms

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;
  }
}
like image 871
Louise McMahon Avatar asked Dec 27 '22 06:12

Louise McMahon


2 Answers

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

like image 146
Lucas Oliveira Avatar answered Dec 29 '22 19:12

Lucas Oliveira


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:

  • There is no need to add element type for id selector id is unique, anything added to it, will increase the overhead of the selector

$("input#username") => $('#username')

like image 24
gdoron is supporting Monica Avatar answered Dec 29 '22 19:12

gdoron is supporting Monica