1

I have custom jQuery validation function, but I'm not able to make it working as I want: If element is empty, I don't want to validate it, but if it's not empty, I want to check, if value is correct.

My custom function looks like this:

$.validator.addMethod("phoneCZ", function(phone_number, element) {
        phone_number = phone_number.replace(/\s+/g, "");

        if(!phone_number.match(/^((\+420)|(\+421))??[0-9]{3}?[0-9]{3}?[0-9]{3}$/)){ 
            return (phone_number.length < 1);
        }
        else {        
            return (phone_number.length >= 9);
        }
    }, "Neplatné telefonní číslo");

Maybe just some describe: Allowed formats are: 123456789 +420123456789 +421123456789

If numbers is not in correct format, I return true, if it's length is 0, else return false. I format is matched, I check, if length is at least 9 characters.

1
  • Add if (phone_number.length === 0) return true; at the top Commented Jan 21, 2015 at 10:52

1 Answer 1

5

There is a method called optional which allows you to do this

$.validator.addMethod("phoneCZ", function (phone_number, element) {
    if (this.optional(element)) {
        return true;
    }
    phone_number = phone_number.replace(/\s+/g, "");

    if (!phone_number.match(/^((\+420)|(\+421))??[0-9]{3}?[0-9]{3}?[0-9]{3}$/)) {
        return (phone_number.length < 1);
    } else {
        return (phone_number.length >= 9);
    }
}, "Neplatné telefonní číslo");

Demo:

$.validator.addMethod("phoneCZ", function(phone_number, element) {
  if (this.optional(element)) {
    return true;
  }
  phone_number = phone_number.replace(/\s+/g, "");

  if (!phone_number.match(/^((\+420)|(\+421))??[0-9]{3}?[0-9]{3}?[0-9]{3}$/)) {
    return (phone_number.length < 1);
  } else {
    return (phone_number.length >= 9);
  }
}, "Neplatné telefonní číslo");

jQuery(function($) {
  var validator = $('#myform').validate({
    debug: true,
    rules: {
      phoneCZ1: {
        phoneCZ: true
      },
      phoneCZ2: {
        required: true,
        phoneCZ: true
      }
    },
    messages: {}
  });
});
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>

<form id="myform" method="post" action="">
  <div>
    <input name="phoneCZ1" />
  </div>
  <div>
    <input name="phoneCZ2" />
  </div>
  <input type="submit" value="Save" />
</form>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.