Categories
JavaScript Vue

Basic Vue Form Validation with VeeValidate

Form validation is a common requirement of in most web apps. This is no different with Vue apps.

Vue doesn’t provide a solution for form validation out of the box. Therefore, we have to find our own solution for form validation.

In this article, we’ll look at how to do basic Vue form validation with VeeValidate.

Getting Started

We can get started by including the VeeValidate library by writing:

<script src="https://unpkg.com/vee-validate@latest"></script>

in our HTML file.

Then we can write:

Vue.component("validation-provider", VeeValidate.ValidationProvider);

to include the validation-provider component in our app. We need to wrap this around our form fields to let VeeValidate do validation on it.

Then we need to define some form validation rules to actually do the form validation.

To do this, we use the VeeValidate.extend function, which takes the rule name string as the first argument, and the callback function that returns the condition for a validate input as the second argument.

For instance, we can use Veelidate.extend as follows to create a rule for for validating that the inputted value is an odd number:

VeeValidate.extend("odd", value => {
  return value % 2 !== 0;
});

In the code above, we check if value % 2 returns 0 or not. If it doesn’t then it’s an odd number.

Likewise, we can do something similar to check if an inputted value is a positive number as follows:

VeeValidate.extend("positive", value => {
  return value >= 0;
});

We can use the rules as follows in a small app with a form field that we can enter something into:

index.js:

Vue.component("validation-provider", VeeValidate.ValidationProvider);

VeeValidate.extend("odd", value => {
  return value % 2 !== 0;
});

VeeValidate.extend("positive", value => {
  return value >= 0;
});
new Vue({
  el: "#app",
  data: {
    value: ""
  }
});

index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>App</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/vee-validate@latest"></script>
  </head>
  <body>
    <div id="app">
      <validation-provider rules="positive|odd" v-slot="{ errors }">
        <input v-model="value" type="text" name="value" />
        <span>{{ errors[0] }}</span>
      </validation-provider>
    </div>
    <script src="index.js"></script>
  </body>
</html>

In the template above, we have a slot that gets the errors object from the validation-provider component which contains the form validation errors messages.

We display the first one by accessing the string on the 0 index of errors.

The rules prop has the rules separated by the | symbol. We applied the positive and odd rules that we defined earlier in index.js

Note that the validation-provider is wrapped around our input. This is required to validate the input. We wrap one validation-provider per input.

Then when type in something that’s not a positive, odd number, we’ll see ‘value is not valid’ displayed.

value is from the value of the name attribute of the input.

Rule Arguments

We can pass in arguments to rule callbacks so that we can do more complex validations. For instance, we can write the following rule to validate that the inputted value is a number bigger than or equal to a certain number:

VeeValidate.extend("min", {
  validate(value, args) {
    return value >= args.num;
  },
  params: ["num"]
});

Then we can apply it as follows:

index.js:

Vue.component("validation-provider", VeeValidate.ValidationProvider);

VeeValidate.extend("min", {
  validate(value, args) {
    return value >= args.num;
  },
  params: ["num"]
});

new Vue({
  el: "#app",
  data: {
    value: ""
  }
});

index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>App</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/vee-validate@latest"></script>
  </head>
  <body>
    <div id="app">
      <validation-provider rules="min:5" v-slot="{ errors }">
        <input v-model="value" type="text" name="value" />
        <span>{{ errors[0] }}</span>
      </validation-provider>
    </div>
    <script src="index.js"></script>
  </body>
</html>

In the code above, we have min:5 to indicate that we want to make sure that our inputted value is 5 or greater.

Conclusion

Validation of Vue forms with VeeValidate is simple. We can do a lot with a few lines of code.

Validation rules are defined with extend. And we use the validation-provider component to validate inputs by wrapping it around the input element.

Also, we can pass in arguments to validation rules to make them more flexible.

Categories
JavaScript Mistakes

More JavaScript Mistakes You May be Making

JavaScript is a language that’s friendlier than many other programming languages in the world. However, it’s still very easy to make mistakes when writing JavaScript code through misunderstanding or overlooking stuff that we already know. By avoiding some of the mistakes below, we can make our lives easier by preventing bugs and typos in our code that bog us down with unexpected results.

Confusing Undefined and Null

JavaScript has both undefined and null for non-values. However, there are quite a few differences between the two. undefined means that the variable may have been declared, but nothing is set to it. A variable can also be explicitly set as undefined. The type of an undefined variable, when checking the type with the typeof operator, will get us the type 'undefined'. Functions that don’t return anything returns undefined. On the other hand, null values have to be explicitly set by functions that return null or just set directly to a variable. When we check an object that has the null value set, we’ll find that the type of it is'object' if a variable has the null value.

For this reason, it’s probably easier to stick to undefined whenever we can when we’re setting variable values to non-values. It reduces confusion and we only have to check that the type of a variable is 'undefined' to see whether it’s undefined. That’s less painful than having two checks, for both null and undefined.

To write functions that return undefined, we don’t have to do anything like the following example:

const f = () => {}

To set a variable that was assigned some other value to undefined, we can write:

x = undefined;

To check if a property value is undefine, we can write:

typeof obj.prop === 'undefined'

or

obj.prop === undefined

To check if a variable is undefined, we can write the following code:

typeof x === 'undefined'

A declared variable that hasn’t been assigned anything automatically has the value undefined.

If we have to check for null, then we can write:

obj.prop === null

or

x === null

for variables. We can’t use the typeof operator for checking null because the data type of null is 'object'.

Confusing Addition and Concatenation

In JavaScript, the + operator is used for both adding two numbers and concatenating strings together. Because JavaScript is a dynamic language, the operands are all automatically converted to the same type before the operation is applied. For example, if we have:

let x = 1 + 1;

then we get two because they’re both numbers. The + operation was used for addition like we expected. However, if we have the following expression:

let x = 1 + '1';

then we get '11' because the first operand was coerced into a string before the + operation is applied. The + operation was used for concatenation instead of addition. When we use the + operator on multiple variables, this makes knowing the type even harder. For example, if we have:

let x = 1;  
let y = 2;  
let z = x + y;

as we expect, we get three because x and y are both numbers. On the other hand, if we have:

let x = 1;  
let y = '2';  
let z = x + y;

then we get '12' because y is a string, so the + operator was used for concatenation instead. To solve this issue, we should convert all the operands to numbers first before using them with the + operator. For example, we should rewrite the above example into the following:

let x = 1;  
let y = '2';  
let z = Number(x) + Number(y);

The code above will get us 3 as the value of z since we converted them both to numbers with the Number factory function first. The Number function takes in any object and returns a number if it can be parsed into a number, or NaN otherwise. An alternative way to do this is to use the new Number(...).valueOf() function, as we do in the following code:

let x = 1;  
let y = '2';  
let z = new Number(x).valueOf() + new Number(y).valueOf();

Since new Number(...) is a constructor that creates an object type, we want to use the valueOf function to convert it back to a primitive type to make sure that what we get is a number type. A shorter way to do this is to write:

let x = 1;  
let y = '2';  
let z = +x + +y;

The + sign in front of a single operand will try to convert the single operand into a number or toNaN if it can’t be converted into a number. It does the same thing as the Number function. We can also convert a variable to a particular type of number. The Number object has a parseInt function to convert a string or object into an integer and a parseFloat function to convert a string or object into a floating-point number. parseInt takes the object you want to convert to a number as the first argument. It also takes a radix as an optional second argument, which is the base of the mathematical numeral systems. If the string starts with 0x, then the radix will be set to 16. If the string starts with anything else, then the radix will be set to 10.

We can use them as in the following examples:

let x = 1;  
let y = '2';  
let z = Number.parseInt(x) + Number.parseInt(y)

Also, we can use the parseFloat function as in the following code:

let x = 1;  
let y = '2';  
let z = Number.parseFloat(x) + Number.parseFloat(y)

We will get 3 in both of the examples above.

Breaking Return Statements Into Multiple Lines

JavaScript closes a statement at the end, so one line code is considered distinct from the other. For example, if we have:

const add = (a, b) => {  
  return  
  a + b;  
}

we get undefined if we run console.log(add(1, 2)); since we ran the return statement, which ended the function execution, before a + b is run. Therefore, a + b will never be run in this function. To fix this, we either have to put the return statement all in one line or use parentheses to surround what we want to return. For example, we can write:

const add = (a, b) => {  
  return a + b;  
}

This will log 3 if we run console.log(add(1, 2)); since we are actually returning the computed result in the function. We can also write:

const add = (a, b) => {  
  return (  
    a + b  
  );  
}

This is handy for returning expressions that might be longer than one line. This will also log 3 if we run console.log(add(1, 2));. For arrow functions, we can also write:

const add = (a, b) => a + b

for single-line functions since the return statement is implicit for single-line arrow functions. We can also write:

const add = (a, b) => (a + b)

to get the same thing. This also works for single-line arrow functions.

In JavaScript, if a statement is incomplete, like the first line of:

const power = (a) => {  
  const  
    power = 10;  
  return a ** 10;  
}

inside the function then the JavaScript interpreter will run the first line together with the second line to get the full statement. So:

const  
  power = 10;

is the same as:

const power = 10;

However, for complete statements like return statements, the JavaScript interpreter will treat them as separate lines. So:

return   
  a ** 10;

is not the same as:

return a ** 10;

Even though JavaScript is a friendly language, it’s still very easy to make mistakes when writing JavaScript code. It’s easy to confuse undefined and null when we aren’t familiar with JavaScript. Because of the dynamic typing nature of JavaScript, operators like the + operator that can do multiple things can easily be converted to a type we don’t expect and produce the wrong result. Also, if statements can be complete on their own, then they shouldn’t be written in their own lines if we want both lines to be together.

Categories
Python

Quick Intro to Python Loops

Python is a convenient language that’s often used for scripting, data science, and web development.

In this article, we’ll look at various kinds of loops that we can use in Python apps to run repeated code.

while Loop Statements

We can use the while loop to run code repeatedly while a condition is True .

It consists of the while keyword, a condition to evaluate, a colon, and then the code to run indented below it.

For example, we can write the following while loop to print a message repeatedly:

x = 0  
while x < 5:  
    print('Hello.')  
    x = x + 1

In the code above, we have x set to 0. Then we use the while loop to print ‘Hello.’. Next, we increment x by 1. We do this repeatedly until x reaches 5.

while loops are useful for looping keeping the loop running until we meet a condition. It doesn’t have to have a finite, determinate amount of iterations.

For example, we can use the while loop until the user guesses the right number as follows:

guess = 0  
while int(guess) != 5:  
  print('Guess a number')  
  guess = input()  
print('You got it')

In the code above, as long as guess doesn’t evaluate to 5 when we convert it to an integer, the while loop will keep running.

Once we entered the right guess, which is 5, the loop will end.

break Statements

The break keyword is used to terminate a loop before the loop ends.

For example, we can rewrite the example above, with break instead of the condition in the while loop as follows:

guess = 0  
while True:  
  if int(guess) == 5:  
    break  
  print('Guess a number')  
  guess = input()  
print('You got it')

In the code above, we have an infinite while loop that has the condition to end the loop with break when we int(guess) returns 5.

The rest of the code works the same way as before.

continue Statements

We can use the continue statement to move on to the next iteration of the loop.

For example, we can use it as follows:

x = 0  
while x < 5:  
  x = x + 1  
  if x == 2:  
    continue  
  print(x)

The code above prints the value of x if it’s not 2. This is because if x is 2, we run continue to skip to the next iteration.

Truthy and Falsy Values

Python has the concept of truthy and falsy values. Truthy values are automatically converted to True when we use them where we have condition checks.

Falsy values are converted to False when we use them for condition checks.

0, 0.0, and '' (the empty string) are all considered False , while all other values are considered True .

For example, we can write a program to prompt users to enter a name and won’t stop until they enter one as follows:

name = ''  
while not name:  
  print('Enter your name:')  
  name = input()  
print('Your name is', name)

In the code above, we use not name to check if name is an empty string or not. If it is, then we keep showing 'Enter your name.' until they enter one.

Once they did, we display the last line with the name .

for Loops and the range() Function

We can use the for loop to loop through a certain number of items.

For example, we can use the for loop with the range function to display numbers from 0 to 4 as follows:

for i in range(5):  
    print(i)

In the code above, the range function returns integers starting from 0 as we and increments the number as we loop up to the number passed into the range function minus 1.

As we can see, the for loop consists of the for keyword, a variable name, the in keyword, a call to the range function, a colon , and then the block of code to run in the loop.

We can also use break and continue statement inside for loops as we did in while loops.

The range function can take 3 arguments, where the first is the starting number and the 2nd argument is the ending number. The loop will terminate when it reaches the ending number minus 1.

The 3rd argument is the increment to increase the variable by in each iteration.

For example, we can write the following code to print all odd numbers between 1 and 10:

for i in range(1, 10, 2):  
    print(i)

We should see:

1  
3  
5  
7  
9

printed because in our range function call, we passed in 1 as the starting number, 10 as the ending number, and 2 to increment i by 2 in each iteration.

Conclusion

We can use while loops to repeatedly run a block of code until a condition is met. This means the loop can run an indeterminate number of iterations.

break is used for ending a loop before it ends. continue is used to skip the loop to the next iteration.

for loops are used for repeatedly run code a finite number of times. It’s used with the range function to do the finite iteration.

Categories
Python

Python String Methods You May Have Missed

Python is a convenient language that’s often used for scripting, data science, and web development.

In this article, we’ll look at how to use Python string methods to manipulate strings.

The upper(), lower(), isupper(), and islower() Methods

The upper method converts all characters of a string to upper case and returns it.

For instance, given the following string:

msg = 'Hello Jane'

Then running msg.upper() returns ‘HELLO JANE’ .

The lower method converts all characters of a string to lower case and returns it.

Therefore, msg.lower() returns ‘hello jane’ .

isupper checks if the whole string is converted to upper case.

For instance, if we have:

msg = 'HELLO JANE'

Then msg.isupper() returns True .

islower checks if the whole string is converted to lower case. For instance, given the following string:

msg = 'hello jane'

Then msg.islower() returns True .

upper and lower can be chained together since they both return strings.

For instance, we can write:

msg.upper().lower()

Then we get:

'hello jane'

returned.

The isX() Methods

There are also other methods for checking for various aspects of the string.

isalpha checks if the whole string consists of only letters and isn’t blank.

For instance, given the following string:

msg = 'hello jane'

Then msg.isalpha() returns False since it has a space in it.

isalnum checks is a string only consists of letters and numbers and returns True if it is.

For example, given the following string:

msg = 'hello'

Then msg.isalnum() returns True .

isdecimal returns True is string consists only of numeric characters and isn’t blank.

For instance, if we have:

msg = '12345'

Then msg.isdecimal() returns True .

isspace returns True if the string only consists of tabs, spaces, and newlines and isn’t blank.

For instance, if we have the following string:

msg = '\n '

Then msg.isspace() returns True .

istitle returns True if the string only has words that begin with an upper case letter followed by only lower case letters.

For instance, if we have the following string:

msg = 'Hello World'

Then msg.istitle() returns True .

The startswith() and endswith() Methods

The startswith method returns True if a string starts with the substring passed in as the argument.

For instance:

'Hello, world'.startswith('Hello')

returns True .

The endswith method returns True if a string ends with the substring passed in as the argument.

For instance:

'Hello, world!'.endswith('world!')

returns True since our string ends with world! .

The join() and split() Methods

The join method combines multiple strings in a string array into one string by the character that it’s called on.

For instance, we can write:

','.join(['apple', 'orange', 'grape'])

which returns ‘apple,orange,grape’.

The string that it’s called on is inserted between the entries.

The split method is used to split a string into a list of substrings by the character that it’s called on.

For instance:

'My name is Jane'.split(' ')

returns [‘My’, ‘name’, ‘is’, ‘Jane’] .

Splitting Strings with the partition() Method

The partition method splits a string into text before and after a separator string.

For instance:

'My name is Jane'.partition('is')

returns:

('My name ', 'is', ' Jane')

We can use the multiple assignment syntax to assign the parts into their own variables since the string is called on is always split into 3 parts.

For instance, we write the folllowing:

before, sep, after = 'My name is Jane'.partition('is')

Then before has the value ‘My name ‘ . sep is 'is' , and after is ' Jane' .

Justifying Text with the rjust(), ljust(), and center() Methods

The rjust method moves a string by the given number of spaces passed in as the argument to the right.

For instance:

'foo'.rjust(5)

returns:

'  foo'

It also takes a second argument to fill in something instead of spaces. For instance, ‘foo’.rjust(5, ‘-’) returns ‘--foo’

ljust adds spaces by the number of that’s passed into the argument to the right of the text.

For instance:

'foo'.ljust(5)

returns:

'foo  '

It also takes a second argument to fill in something instead of spaces. For instance, ‘foo’.ljust(5, ‘*’) returns ‘foo**’

The center method adds the number of spaces passed in as the argument to the left and the right of the string.

For instance:

'foo'.center(15)

returns:

'      foo      '

It also takes a second argument to fill in something instead of spaces. For instance, ‘foo’.center(5, ‘*’) returns ‘*foo*’ .

Conclusion

Python has string methods to convert strings to upper and lower case.

We can also add spaces and other characters to the string.

Multiple strings can also be joined together. Also, they can be split off into multiple strings.

There’re also many methods to check strings for various characteristics.

Categories
Python

Using Regex with Python

Python is a convenient language that’s often used for scripting, data science, and web development.

In this article, we’ll look at how to use regex with Python to make finding text easier.

Finding Patterns of Text with Regular Expressions

Regular expressions, or regexes, are descriptions for a pattern of text.

For instance, \d represents a single digit. We can combine characters to create regexes to search text.

To use regexes to search for text, we have to import the re module and then create a regex object with a regex string as follows:

import re  
phone_regex = re.compile('\\d{3}-\d{3}-\d{4}')

The code above has the regex to search for a North American phone number.

Then if we have the following string:

msg = 'Joe\'s phone number is 555-555-1212'

We can look for the phone number inside msg with the regex object’s search method as follows:

import re  
phone_regex = re.compile('\d{3}-\d{3}-\d{4}')  
msg = 'Joe\'s phone number is 555-555-1212'  
match = phone_regex.search(msg)

When we inspect the match object, we see something like:

<re.Match object; span=(22, 34), match='555-555-1212'>

Then we can return a string representation of the match by calling the group method:

phone = match.group()

phone has the value '555-555-1212' .

Grouping with Parentheses

We can use parentheses to group different parts of the result into its own match entry.

To do that with our phone number regex, we can write:

phone_regex = re.compile('(\d{3})-(\d{3})-(\d{4})')

Then when we call search , we can either get the whole search string, or individual match groups.

group takes an integer that lets us get the parts that are matched by the groups.

Therefore, we can rewrite our program to get the whole match and the individual parts of the phone number as follows:

import re  
phone_regex = re.compile('(\d{3})-(\d{3})-(\d{4})')  
msg = 'Joe\'s phone number is 123-456-7890'  
match = phone_regex.search(msg)  
phone = match.group()  
area_code = match.group(1)  
exchange_code = match.group(2)  
station_code = match.group(3)

In the code above, phone should be ‘123–456–7890’ since we passed in nothing to group. Passing in 0 also returns the same thing.

area_code should be '123' since we passed in 1 to group , which returns the first group match.

exchange_code should be '456' since we passed in 2 to group , which returns the 2nd group match.

Finally, station_code should be '7890' since we passed in 3 to group , which returns the 3rd group match.

If we want to pass in parentheses or any other special character as a character of the pattern rather than a symbol for the regex, then we have to put a \ before it.

Matching Multiple Groups with the Pipe

We can use the | symbol, which is called a pipe to match one of many expressions.

For instance, we write the following to get the match:

import re  
name_regex = re.compile('Jane|Joe')  
msg = 'Jane and Joe'  
match = name_regex.search(msg)  
match = match.group()

match should be 'Jane' since this is the first match that’s found according to the regex.

We can combine pipes and parentheses to find a part of a string. For example, we can write the following code:

import re  
snow_regex = re.compile(r'snow(man|mobile|shoe)')  
msg = 'I am walking on a snowshoe'  
snow_match = snow_regex.search(msg)  
match = snow_match.group()  
group_match = snow_match.group(1)

to get the whole match with match , which has the value 'snowshoe' .

group_match should have the partial group match, which is 'shoe' .

Optional Matching with the Question Mark

We can add a question mark to the end of a group, which makes the group optional for matching purposes.

For example, we can write:

import re  
snow_regex = re.compile(r'snow(shoe)?')  
msg = 'I am walking on a snowshoe'  
msg_2 = 'I am walking on snow'  
snow_match = snow_regex.search(msg)  
snow_match_2 = snow_regex.search(msg_2)

Then snow_match.group() returns 'snowshoe' and snow_match.group(1) returns 'shoe' .

Since the (shoe) group is optional, snow_match_2.group() returns 'snow' and snow_match_2.group(1) returns None .

Conclusion

We can use regexes to find patterns in strings. They’re denoted by a set of characters that defines a pattern.

In Python, we can use the re module to create a regex object from a string.

Then we can use it to do searches with the search method.

We can define groups with parentheses. Once we did that, we can call group on the match object returned by search.

The group is returned when we pass in an integer to get it by their position.

We can make groups optional with a question mark appended after the group.