Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Friday, October 16, 2020

JavaScript Regular Expression


A regular expression is a string that describes a pattern e.g., email addresses and phone numbers.

In JavaScript, regular expressions are objects. JavaScript provides the built-in RegExp type that allows you to work with regular expressions effectively.

Regular expressions are useful for searching and replacing strings that match a pattern. They have many useful applications.

For example, you can use regular expressions to extract useful information in web scraping like product prices. Or you can use regular expressions to validate form fields like email addresses and phone numbers.

 

Creating a regular expression

To create a regular expression in JavaScript, you enclose its pattern in forward-slash ( / ) characters like this:

   let re = /hi/;

Note that a regular expression doesn’t have single quotes or double quotes like a regular string.

 

Or you can use the RegExp constructor:

    let re = new RegExp('hi');

Both regular expressions are the instances of the RegExp type. They match the string 'hi'.


Testing for matching

The RegExp object has many useful methods. One of them is the test() method that allows you to test if a string contains a match of the pattern in the regular expression.

The test() method returns true if the string the argument contains a match.

The following example shows how to use the test() method:

    let re = /hi/;

    let result = re.test('hi John');
    
    console.log(result); // true
 

Using pattern flags

Besides a pattern, a RegExp object also accepts an optional flag parameter. Flags are settings that change the searching behavior.

1) The ignore flag (i)

Regular expressions have many flags. For example, the ignore or i flag ignores cases when searching.

By default, searches are case-sensitive. For example /hi/ only matches the string hi not Hi, or HI.

To search for a string with any cases, you use the i flag:

    let re = /hi/i;

    let result = re.test('hi John');
    
    console.log(result); // true

In this example, the /hi/i will match any string hi, Hi, and HI.

The following shows how to use the pattern flag in the RegExp constructor:

    let re = new RegExp('hi','i');

    let result = re.test('HI John'); 

    console.log(result); // true

2) The global flag (g)

Another commonly used flag is the global or g flag.

Without the global flag, the RegExp object only checks if there is a match in a string and returns the first match.

When the g flag is available, the RegExp looks for all matches and returns all of them.

It’s possible to combine flags e.g., gi flags combine the ignore (i) and the global flag (g) flags.

The exec() method of the RegExp performs a search for a match in a string and returns an array that contains detailed information about the match.

The exec() method returns null if it could not find any match. However, it returns a single match at once. To get all matches, you need to execute the exec() multiple times.

The following example uses the exec() method with a while loop to return all the matches:

    let message = "Hi, are you there? hi, HI...";


    let re = /hi/gi;

    let matches = [];

    let match;

    do {
    match = re.exec(message);

    if (match) {
        matches.push(match);
    }
    } while (match != null);

    console.dir(matches);

Output:



How it works:

·        First, declare a message string that will be used for searching.

·      Then, create a regular expression object with the pattern /hi/gi. The ignore flag (i) allows re object to ignore cases when executing the search and the global flag (g) instructs the re object to find all matches, not just the first one.

·       Third, execute the exec() method until no match found.

·       Finally, show the result array in the console.

 

Searching strings

The method str.match(regexp) returns all matches of regexp in the string str.

To find all matches, you use the global flag ( g ). And to find the matches regardless of cases, you use the ignore flag ( I ).

The following example shows how to use the match() method:

    let str = "Are you Ok? Yes, I'm OK";


    let result = str.match(/OK/gi);

    console.log(result);

Output: 
    
["Ok""OK"];

Replacing strings

The following example uses the replace() method to replace the first occurrence of the string 'Ok' in the string str:

    let str = "Are you OK? Yes, I'm OK.";


    let result = str.replace("Ok""fine");

    console.log(result);

Output:

Are you fine? Yes, I'm OK


To replace all occurrences of OK, you use a regular expression with the global flag (g):

    let str = "Are you OK? Yes, I'm OK.";


    let result = str.replace(/OK/g"fine");

    console.log(result);

Output:

Are you fine? Yes, I'm fine.


The following example uses both ignore and global flags to replace all occurrences of OK regardless of cases with the string fine:

    let str = "Are you Ok? Yes, I'm OK.";


    let result = str.replace(/OK/gi"fine"); 

    console.log(result);

Output:

Are you fine? Yes, I'm fine.

 

Summary

  • Use / / or RegExp constructor to create a regular expression.
  • Use the pattern flag e.g., ignore ( I ) and global ( g ) to modify the matching behavior.
  • Use the RegExp.test() method to determine if a pattern is found in a string.
  • Use the RegExp.exec() method to find the match and return an array that contains the information of the match.
  • Some string methods such as match() and replace() support the regular expressions.

 

Thursday, October 15, 2020

JavaScript Forms


Quite regularly, you meet a website where users enter information into a form before sending it to the server, for example, the account registration form. The information that the user enters into the form needs to be validated to ensure data rationality. 
Some examples of authentication:

  • Check to ensure that the data is not empty.
  • Check email format
  • Check telephone number format

There are basically 3 ways for data validation:

  1. form data will be sent to the server, and validation will be done on the server side.
  2. form data will be validated on the client side by using Javascript, which helps server not have to work too much and increase performance for the application.
  3. Use both above methods to validate form.

 

1- Form Validation

JavaScript provides facility to validate the form on the client-side so data processing will be faster than server-side validation. Most of the web developers prefer JavaScript form validation. Through JavaScript, we can validate name, password, email, date, mobile numbers and more fields.

Form validation generally performs two functions.

  • Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are filled in. It would require just a loop through each field in the form and check for data.
  • Data Validation − Secondly, the data that is entered must be checked for correct form and value. Your code must include appropriate logic to test correctness of data.

In this topic, I will discuss using Javascript to validate form. Below is the illustration of the program's behavior when the user clicks the Submit button. 

1.   You have to register a function in combination with the onsubmit event of form. The duty of this function is to check the data which a user has entered in form, and return true if all the information entered by the user is valid and vice versa return false.

2.    When the user clicks Submit, the function in combination with the onsubmit event will be called.

3.   If the function in combination with the onsubmit event  returns true, the data of form will be sent to the server and vice versa the Submit action will be canceled.

 

2- Simple Example

OK, this is a simple example helping you understand the operating rules of  Form before practicing more complex examples.

The action attribute of  <form> is used to specify the page to which data will be given or  in other words, this is the page that will process the data sent from the <form> of the current page.  

The pages processing the data sent from form are usually written by Servlet/JSP, PHP technology or technology on the Server-side instead of an HTML page. However, here I do not mention data processing on the server-side in this topic.  

simple-validation-example.html

<!DOCTYPE html>

<html>
  <head>
    <title>Hello Javascript</title>

    <script type="text/javascript">
      function validateForm() {
        var u = document.getElementById("username").value;
        var p = document.getElementById("password").value;

        if (u == "") {
          alert("Please enter your Username");
          return false;
        }

        if (p == "") {
          alert("Please enter you Password");
          return false;
        }

        alert("All datas are valid!, send it to the server!");
        return true;
      }
    </script>
  </head>

  <body>
    <h2>Enter your Username and Password</h2>

    <div style="border: 1px solid #ddd; padding: 5px">
      <form
        method="GET"
        action="process-action.html"
        onsubmit="return validateForm()" >
        Username: <input type="text" name="username" id="username" />
        <br /><br />
        Password: <input type="password" name="password" id="password" />
        <br /><br />
        <button type="submit">Submit</button>
      </form>
    </div>
  </body>
</html>

process-action.html

 <!DOCTYPE html>

<html>
  <head>
    <title>Process Action</title>
  </head>
  <body>
    <h3>Process Action Page</h3>
    OK, I got data!
    <br /><br />
    <a href="javascript:history.back();">[Go Back]</a>
  </body>
</html>

Output

 



3- Access the form data

·         Access field data through the field ID 

<input type="text" id="username" />
<input type="password" id="password" />

// Access field via ID: 
var uInput = document.getElementById("username"); 
var uValue= uInput.value;

 

·         Access Form fields through the name attribute:


<form name="myForm" ...>
  <input type="text" name="username" />
  <input type="password" name="password" />
  <button type="submit">Submit</button>
</form>

  // Get form via form name:
  var myForm = document.forms["myForm"];
  var u = myForm["username"].value;
  var p = myForm["password"].value;

 

When a user enters inaccurate data on a form field, you should notify the user and focus on that field. 

validation-example1.html 


<!DOCTYPE html>
<html>
  <head>
    <title>Validation</title>
    <script type="text/javascript">
      function validateForm() {
        // Get form via form name:

        var myForm = document.forms["myForm"];
        var u = myForm["username"].value;
        var p = myForm["password"].value;

        if (u == "") {
          alert("Please enter your Username");
          myForm["username"].focus(); // Focus
          return false;
        }

        if (p == "") {
          alert("Please enter you Password");
          myForm["password"].focus(); // Focus
          return false;
        }

        alert("All datas are valid!, send it to the server!");
        return true;
      }
    </script>
  </head>
  <body>
    <h2>Enter your Username and Password</h2>

    <div style="border: 1px solid #ddd; padding: 5px">
      <form
        name="myForm"
        method="GET"
        action="process-action.html"
        onsubmit="return validateForm()"  >
        Username: <input type="text" name="username" />
        <br /><br />

        Password: <input type="password" name="password" />
        <br /><br />

        <button type="submit">Submit</button>
      </form>
    </div>
  </body>
</html>

 

Example-2

Ask a user to enter a number between 0 and 10. 

validation-number-example.html

<!DOCTYPE html>

<html>
  <head>
    <title>Validation</title>

    <script type="text/javascript">
      function validateForm() {
        var myField = document.getElementById("myNumber");

        var value = myField.value;

        if (value == "" || isNaN(value) || value < 0 || value > 10) {
          alert("Invalid input!");
          myField.focus();
          return false;
        }
        return true;
      }
    </script>
  </head>

  <body>
    <h2>Enter a Number between 0 and 10</h2>

    <div style="border: 1px solid #ddd; padding: 5px">
      <form
        name="myForm"
        action="process-action.html"
        onsubmit="return validateForm()"  >
        Number: <input type="text" id="myNumber" />
        <br /><br />
        <button type="submit">Submit</button>
      </form>
    </div>
  </body>
</html>


 

4- Submit through Javascript

Clicking  <button type="submit"> or  <input type="submit"> inside  form helps you to send the data of this  form to the server, however, you can also do it through  Javascript. 

javascript-submit-example.html 


<!DOCTYPE html>
<html>
  <head>
    <title>Javascript Submit</title>
    <script type="text/javascript">
      function validateForm() {
        var name = document.forms["myForm"]["fullName"].value;

        if (name == "") {
          alert("Please enter your name");
          return false;
        }
        return true;
      }

      function submitByJavascript() {
        var valid = validateForm();

        if (!valid) {
          return;
        }

        var myForm = document.forms["myForm"];
        myForm.submit();
      }
    </script>
  </head>
  <body>
    <h2>Submit a from with Javascript</h2>
    <div style="border: 1px solid #ddd; padding: 5px">
      <form
        name="myForm"
        action="process-action.html"
        onsubmit="return validateForm()" >
        Your Name: <input type="text" name="fullName" value="" />
        <br /><br />
        <button type="submit">Submit</button>
      </form>
    </div>
    <br />
    <!-- A Button outside the form -->
    Button outside the form:

    <button onclick="submitByJavascript()">Click Me to submit form</button>
  </body>
</html>

 

5- Validate automatically

The browser can automatically validate several types of data on the form, such as adding a required attribute to a form field to tell the browser that this field is mandatory. The browser will automatically check and notify an user if an user does not enter that field. 

Note: Too old browsers such as IE version 9 or older does not support automatic validation.

required-example.html 


<!DOCTYPE html>
<html>
  <head>
    <title>Required</title>
  </head>
  <body>
    <h2>Required attribute</h2>
    <div style="border: 1px solid #ddd; padding: 5px">
      <form
        name="myForm"
        action="process-action.html"
        onsubmit="return validateForm()"   >
        Your Name: <input type="text" name="fullName" value="" required />
        <br /><br />
        <button type="submit">Submit</button>
      </form>
    </div>
  </body>
</html>



Pattern Validation [Example-1]

attr-pattern-example.html

<!DOCTYPE html>

<html>
  <head>
    <title>pattern attribute</title>
  </head>
  <body>
    <h2>Attribute: pattern</h2>
    <div style="border: 1px solid #ddd; padding: 5px">
      <form name="myForm" action="process-action.html">
        Country code:
        <input
          type="text"
          name="countryCode"
          pattern="[A-Za-z]{2}"
          title="Two letter country code" />

        <br /><br />
        <button type="submit">Submit</button>
      </form>
    </div>
  </body>
</html>



Pattern Validation [Example-2]

Ask an user to enter a password having at least 8 characters.

attr-pattern-example2.html 


<!DOCTYPE html>
<html>
  <head>
    <title>pattern attribute</title>
  </head>
  <body>
    <h2>Attribute: pattern</h2>
    <div style="border: 1px solid #ddd; padding: 5px">
      <form name="myForm" action="process-action.html">
        Password:
        <input
          type="password"
          name="password"
          pattern=".{8,}"
          title="8 or more characters"  />

        <br /><br />
        <button type="submit">Submit</button>
      </form>
    </div>
  </body>
</html>



Password Pattern Validation 

Ask an user to enter a strong password, having at least 8 characters, at least one uppercase, and at least one lowercase. 

attr-pattern-password-example.html 


<!DOCTYPE html>
<html>
  <head>
    <title>pattern attribute</title>
  </head>
  <body>
    <h2>Attribute: pattern</h2>
    Password must contain 8 or more characters that are of at least 
one number,and one uppercase and lowercase letter:
    <br /><br />
    <div style="border: 1px solid #ddd; padding: 5px">
      <form name="myForm" action="process-action.html">
        Password:
        <input
          type="password"
          name="password"
          pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"
          title="Invalid password!"   />

        <br /><br />
        <button type="submit">Submit</button>
      </form>
    </div>
  </body>
</html>

Email Pattern Validation 

Ask a user to enter an email address, use the pattern attribute to ensure that the user enters an email in the correct format. 

attr-pattern-email-example.html 


<!DOCTYPE html>
<html>
   <head>
      <title>pattern attribute</title>
   </head>
   <body>
      <h2>Attribute: pattern</h2>
      <div style="border:1px solid #ddd; padding: 5px;">
         <form name="myForm" action="process-action.html">
            Email:
            <input type="password" name = "password"
              pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$"
              title="Invalid password!"/>
            <br/><br/>
            <button type="submit">Submit</button>
         </form>
      </div>
   </body>
</html>