1

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.

2
  • note, that your function returns true if the username is bad, otherwise false. This is counter-intuitive. Commented Jun 5, 2019 at 17:20
  • Please do not use the Code Snippet feature on incomplete code that cannot run a demo. Edited. Thanks. Commented Jun 10, 2019 at 15:36

1 Answer 1

2

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
});
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.