Matheus Batista
Matheus Batista

Reputation: 305

Validating fields with js/jQuery

I'm having some trouble while validating a simple input text field. What I want is to prevent some specific cases, but I just can't find a solution.

I need to prevent the following:

I searched for methods to keep numbers out and found this regex /^[a-za-z]+$/, which worked.

But I couldn't find a solution to the blank spaces issue.

Upvotes: 0

Views: 43

Answers (1)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48610

If you are using jQuery validaton, the following may help you.

First, you could change your pattern to the following:

const pattern = /^[A-Z][a-z']+ [A-Z][a-z']+$/;

Then add a method to the validation plugin check for your pattern.

$.validator.methods.checkFullName = function(value, element) {
  return this.optional(element) || /^[A-Z][a-z']+ [A-Z][a-z']+$/.test(value);
}

Caveat: As for the length limitation, that can be up for debate. Some names can be shorter than 3 characters. Just make them require at least capital letter for the beginning of each name and one or many lower-case. If you need a name like "O'Hare" then you will need to change it to something like the following: /^[A-Z][A-Za-z'\.]* [A-Z][A-Za-z']*$/. This way a name like "A. O'Hare" will be valid. The pattern is completely up to you, but I would try to find a more common pattern. It may probably be a better idead to just validate first and last names individually.

Full example

I adapted the following example from:

"How to Set Up Basic jQuery Form Validation in Two Minutes" – SitePoint

/* jquery.validator-methods-checkFullName.js */
(function($) {
  $.validator.methods.checkFullName = function(value, element) {
    return this.optional(element) || /^[A-Z][a-z']+ [A-Z][a-z']+$/.test(value);
  }
})(jQuery);


$(function() {
  $("form[name='registration']").validate({
    rules: {
      fullname: {
        required: true,
        checkFullName: true
      },
      email: {
        required: true,
        email: true
      },
      password: {
        required: true,
        minlength: 8
      }
    },
    messages: {
      fullname: "Please enter your full name",
      password: {
        required: "Please provide a password",
        minlength: "Your password must be at least 8 characters long"
      },
      email: "Please enter a valid email address"
    },
    submitHandler: function(form) {
      form.submit();
    }
  });
});
@import url("https://fonts.googleapis.com/css?family=Open+Sans");

/* Styles */

* {
  margin: 0;
  padding: 0;
}

body {
  font-family: "Open Sans";
  font-size: 14px;
}

.container {
  width: 500px;
  margin: 25px auto;
}

form {
  padding: 20px;
  background: #2c3e50;
  color: #fff;
  -moz-border-radius: 4px;
  -webkit-border-radius: 4px;
  border-radius: 4px;
}

form label,
form input,
form button {
  border: 0;
  margin-bottom: 3px;
  display: block;
  width: 100%;
}

form input {
  height: 25px;
  line-height: 25px;
  background: #fff;
  color: #000;
  padding: 0 6px;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

form button {
  height: 30px;
  line-height: 30px;
  background: #e67e22;
  color: #fff;
  margin-top: 10px;
  cursor: pointer;
}

form .error {
  color: #ff0000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js"></script>
<!-- See: https://www.sitepoint.com/basic-jquery-form-validation-tutorial/ -->
<div class="container">
  <h2>Registration</h2>
  <form action="" name="registration">

    <label for="fullname">First Name</label>
    <input type="text" name="fullname" id="fullname" placeholder="John Doe" />

    <label for="email">Email</label>
    <input type="email" name="email" id="email" placeholder="[email protected]" />

    <label for="password">Password</label>
    <input type="password" name="password" id="password" placeholder="&#9679;&#9679;&#9679;&#9679;&#9679;" />

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

  </form>
</div>

The additional methods plugin, adds a pattern method.

Just make sure you include the additional-methods.min.js script.

$(function() {
  $("form[name='registration']").validate({
    rules: {
      fullname: {
        required: true,
        pattern: /^[A-Z][a-z']+ [A-Z][a-z']+$/
      },
      email: {
        required: true,
        email: true
      },
      password: {
        required: true,
        minlength: 8
      }
    },
    messages: {
      fullname: {
        pattern: "Please enter your full name"
      },
      password: {
        required: "Please provide a password",
        minlength: "Your password must be at least 8 characters long"
      },
      email: "Please enter a valid email address"
    },
    submitHandler: function(form) {
      form.submit();
    }
  });
});
@import url("https://fonts.googleapis.com/css?family=Open+Sans");

/* Styles */

* {
  margin: 0;
  padding: 0;
}

body {
  font-family: "Open Sans";
  font-size: 14px;
}

.container {
  width: 500px;
  margin: 25px auto;
}

form {
  padding: 20px;
  background: #2c3e50;
  color: #fff;
  -moz-border-radius: 4px;
  -webkit-border-radius: 4px;
  border-radius: 4px;
}

form label,
form input,
form button {
  border: 0;
  margin-bottom: 3px;
  display: block;
  width: 100%;
}

form input {
  height: 25px;
  line-height: 25px;
  background: #fff;
  color: #000;
  padding: 0 6px;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

form button {
  height: 30px;
  line-height: 30px;
  background: #e67e22;
  color: #fff;
  margin-top: 10px;
  cursor: pointer;
}

form .error {
  color: #ff0000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/additional-methods.min.js"></script>
<!-- See: https://www.sitepoint.com/basic-jquery-form-validation-tutorial/ -->
<div class="container">
  <h2>Registration</h2>
  <form action="" name="registration">

    <label for="fullname">First Name</label>
    <input type="text" name="fullname" id="fullname" placeholder="John Doe" />

    <label for="email">Email</label>
    <input type="email" name="email" id="email" placeholder="[email protected]" />

    <label for="password">Password</label>
    <input type="password" name="password" id="password" placeholder="&#9679;&#9679;&#9679;&#9679;&#9679;" />

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

  </form>
</div>


If you wanted to properly add new methods, you achieve this using:

/* jquery.validator-methods-regex.js */
(function($) {
  $.validator.addMethod('regex', function(value, element, regex) {
    var re = typeof regex == 'string' ? new RegExp(regex) : regex;
    return this.optional(element) || re.test(value);
  });
})(jQuery);


$(function() {
  $("form[name='registration']").validate({
    rules: {
      fullname: {
        required: true,
        regex: /^[A-Z][a-z']+ [A-Z][a-z']+$/
      }
    }
  });
});

Upvotes: 1

Related Questions