0

Im using jquery validate and I wish to add a method that input text cannot contain ".com"

Im tried:

    //.com Validator
    $.validator.addMethod('dotcom', function(value, element) {
        return this.optional(element) || (!value.match(/[.com]/) && value.match(/[.com]/));
    },
    dotcom);

But this doesn't work, any suggestion to do that ? thanks

1 Answer 1

1

It looks like your regex test is wrong. Try

var dotcom = 'Value cannot contain `.com`'
$.validator.addMethod('dotcom', function(value, element) {
  return this.optional(element) || !/\.com/.test(value);
}, dotcom);


$('form').validate({
  rules: {
    site: {
      dotcom: true
    }
  }
})

$('button').click(function() {
  $('form').valid();
  return false;
})
<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>
  <div>
    <input name="site" />
  </div>
  <button>Save</button>
</form>

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

7 Comments

if I want input must have "com." so how ? I tried /\com./.test(value); but doesn't work
@TheSmile try return this.optional(element) || /\.com/.test(value);
but if I want "com." not ".com"
@TheSmile then return this.optional(element) || /com/.test(value);
@TheSmile sorry return this.optional(element) || /com\./.test(value);
|

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.