M0136466 M0136466 -4 years ago 101
jQuery Question

how to check if string contain numbers?

I am using Jquery validation method and I want to check if string(firstname or lastname) contain numbers

my code:


<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>

<link href="runnable.css" rel="stylesheet" />
<!-- Load jQuery and the validate plugin -->
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>

<!-- jQuery Form Validation code -->

// When the browser is ready...
$(function() {

// Setup form validation on the #register-form element

// Specify the validation rules
rules: {
firstname: "required",
lastname: "required",
email: {
required: true,
email: true
password: {
required: true,
minlength: 5
agree: "required"

// Specify the validation error messages
messages: {
firstname: "Please enter your first name",
lastname: "Please enter your last name",
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
email: "Please enter a valid email address",
agree: "Please accept our policy"

submitHandler: function(form) {


<h1>Register here</h1>

<!-- The form that will be parsed by jQuery before submit -->
<form action="" method="post" id="register-form" novalidate="novalidate">

<div class="label">First Name</div><input type="text" id="firstname" name="firstname" /><br />
<div class="label">Last Name</div><input type="text" id="lastname" name="lastname" /><br />
<div class="label">Email</div><input type="text" id="email" name="email" /><br />
<div class="label">Password</div><input type="password" id="password" name="password" /><br />
<div style="margin-left:140px;"><input type="submit" name="submit" value="Submit" /></div>



how to do that??

I want if someone fill his/her first name or last name with numbers or it contain numbers like (1234 or john1234 or 1234john or jo1234hn ..ect) get massage that name is incorrect

Answer Source

You can do this without regular expressions and adding a custom method to the jQuery validator like

    function (value, element) {

        var numArray = 
            ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
        var containsNumber = false;

        $.each(value.split(''), function () {
            if (numArray.indexOf($(this)[0]) > -1) {
                containsNumber = true;
                return false;

        return !containsNumber;


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download