Regex for Real Time Form Validation

In this lesson

  • Import Regex utility class
  • Create Color binding
  • Add validation in property setter

Transcript

Tap on time to skip ahead

00:11

Giving users real time feedback on what they are entering in a form field is another way that we can speed up any sort of data entry process, as well as try to reduce friction between the user and our systems, or application, if you will.  For example, it would be nice as I typed in my email field if it were to let me know if I was entering in a valid email address or not. This could also work for things like phone numbers, zip codes, passwords of the correct strength, etc. We’re going to take a quick look at how we can implement something like this with Regex in just a minute or two.

00:52

The first thing I’m going to do is go into our LoginViewModel and I’m going to add a new property. This property is going to be a color and I’m going to call it EmailBackgroundColor.  We’re going to bind our login pages email entry to this color. I’m going to say, “BackgroundColor = Binding.” Just to make sure I don’t do a typo or anything I’m going to copy and paste from here. Ok. Now, if I instantiate this variable to have the color red, when I run our application, we’ll see that our login field is in fact red.

01:49

Let’s wire this up to actual user input. In between videos, I added a new class called Regex Util. This is just a handy little class that I use between projects that will return regular expressions for email address, minimum length, etc. This class is really easy to use. If I go into the setter of my email address, I can say, “EmailBackgroundColor = RegexUtil.” Probably need to import that. ValidEmailAddress IsMatch. Then we’re going to pass this, the value that was passed. Then I’m going to use it in my if clause. I’m going to say, “If it is a match, then we want this color to be white. Otherwise, we want it to be red.”

02:45

Now, as we run our application, we’ll see that it starts off red because we have not entered a valid email address. I’m going to type Ben@rendr.io. And it doesn’t work. Why doesn’t it work?

03:05

The reason that this doesn’t work is that we forgot to dispatch our property change event. This basically lets the forms binding mechanism know that, “Hey, something has changed. You might want to update yourself.” Now if we run our application- as we see as I type a valid email address, we get instant feedback that let’s us know whether or not we are imputing something correctly. This again, is a way that we can make our application seem quick and responsive to our users.