victorjonsson / jQuery-Form-Validator

[DISCONTINUED] jQuery plugin that makes it easy to validate user input while keeping your HTML markup clean from javascript code.
971 stars 475 forks source link

Validate only URL from certain host #449

Open mozzillation opened 8 years ago

mozzillation commented 8 years ago

is there a method for only accept urls from a particular host? for ex.: validate if url is from www.github.com

victorjonsson commented 8 years ago

This question has come up now and again. You can make a custom validator like so:


<input data-validation="url github_url" ... />

<script>
$.formUtils.addValidator({
  name : 'github_url',
  validatorFunction : function(value, $el, config, language, $form) {
    return value.indexOf('https://github.com/') == 0;
  },
  errorMessage : 'This is not an url to github',
});

$.validate();
</script>

You can also use a regular expression together with the custom validator:

http://jsbin.com/yopogoguje/edit?html,output

<form>
  <p>
    <strong>Github link:</strong> <br>
    <input type="text"
         data-validation="url custom"    
         data-validation-regexp="^(https|http)://www.github.com|https://github.com"
        data-validation-error-msg="Only github URL´s are allowed">
  </p>
  <p>
    <input type="submit">
  </p>
</form>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/jquery.form-validator.min.js"></script>
<script>
  $.validate();
</script>

How ever, I think that the logic module should have a generic validator that checks that a values begins with a certain set of characters. The implementation could look something like:

<input 
   data-validation="url startsWith" 
   data-validation-starts-with="https://www.github.com/|https://github.com/"
   data-validation-error-msg="You can only enter github links" 
/>

<script>
  $.validate({
     modules: 'logic'
  });
</script>