0

I'm working on a custom rule (jQuery Validation Plugin), which it checks the first & last letter of string (input).

Rule : User can not enter . or _ at first or end of the input.

I have written a function with my pure javascript knowledge. I don't know how to use the function in this jQuery plugin !

My code :

    var text = document.getElementById('UserName').value;
    var firstChar = text.slice(0, 1);
    var lastChar = text.slice(-1);

    function validUser() {

        if (firstChar === '.' || firstChar === '_' || lastChar === '.' || lastChar === '_') {
            return true;
        } else {
            return false;
        }

    }

I have seen this link : https://jqueryvalidation.org/jQuery.validator.addMethod/

But still I don't know how can I use my own code.

Sparky
  • 98,165
  • 25
  • 199
  • 285
  • note, that your function returns true if the username is bad, otherwise false. This is counter-intuitive. – Steve0 Jun 05 '19 at 17:20
  • Please do not use the Code Snippet feature on incomplete code that cannot run a demo. Edited. Thanks. – Sparky Jun 10 '19 at 15:36

1 Answers1

1

As per the documentation for the library you linked https://jqueryvalidation.org/jQuery.validator.addMethod/

Define it like this,

jQuery.validator.addMethod("validUser", function(value, element) {
  //value is the val in the textbox, element is the textbox.
  var firstChar = value.slice(0, 1);
  var lastChar = value.slice(-1);

 if (firstChar === '.' || firstChar === '_' || lastChar === '.' || lastChar === '_') 
 {
    return true;
 } else {
    return false;
 }
}, 'Please enter a valid username.');

And then use it like this;

$("#UserName").rules("add", {
   validUser: true
});
Steve0
  • 2,233
  • 2
  • 13
  • 22
  • FYI - once defined, the custom rule can be used just like any other rule. There is absolutely no requirement to declare it with the `.rules()` method. It can be inside of the `rules` object of `.validate()`, a class name, part of a compound rule, etc. – Sparky Jun 10 '19 at 15:39