Hep me understand this jquery

Working on a project for a form validation and my partner started to use jquery. He’s now asleep and you guys are all I have left. I can see what he put and get the idea but I don’t quite understand the specifics at hand. What he’s saying. Can someone explain this to me?

var $form = $("form"), $successMsg = $(".alert"); $.validator.addMethod("letters", function(value, element) { return this.optional(element) || value == value.match(/^[a-zA-Z\s]*$/); });

Not sure fit that’s the actual line of code, or you put the code without three backticks for formatting.
If this is actually how the code is formatted, id tell you partner to format his code better, shoving everything on one line doesn’t make you look like a better coder, its just a pain in the butt to read for us humans ;D

Regardless this is the formatted code:

var $form = $("form"),
    $successMsg = $(".alert");
$.validator.addMethod("letters", function(value, element) {
    return this.optional(element) || value == value.match(/^[a-zA-Z\s]*$/);
});

So lets break it down line by line.

var $form = $("form"),
    $successMsg = $(".alert");

These two lines are short hand for:

var $form = $("form");
var $successMsg = $(".alert");

They are saving the jquery selections so every time he uses these later, they don’t have to “find” the element(s) in the dom any more, as its already saved. This is a best-practice so you aren’t having jquery looking through the dom for the same elements over and over again. (He doesn’t seem to use this code later in the snippet so thats the last mention of these two variables)

The rest of the code isn’t bare-bones jquery, rather its part of a plugin for jquery for validation

$.validator.addMethod("letters", function(value, element) {
    return this.optional(element) || value == value.match(/^[a-zA-Z\s]*$/);
});

It mainly appears your partner implemented a custom “validator” using the plugin that uses this regex:
/^[a-zA-Z\s]*$/
Now I’m unsure if you know what regex’s(Formally known as Regular Expressions) are, so here’s an Mdn article on the topic. The TLDR version is mainly this regex will be used by the match function to only allow letters to be valid inputs.

Hopefully that helps :smiley:
PS You can play around with regex’s online, to see their behavior in real time. I use this site