Why does this regular expression work outside of the javascript function, but not inside?

Ok, so I'm new to regex, not to mention Javascript.

I am trying to work on a form validation project, and I found a site on which they have a list of useful examples of regular expressions for various things here , which has a few for email authentication, which I am trying now.

In any case, following this example to validate the form in w3schools, I was able to get it to work correctly using their example, and the regular expression works outside the javascript function, but for some reason, when I call it inside the function, it returns undefined ,

Here is my code:

<html>
  <head>
    <title>formzz validate-jons</title>
      <script type="text/javascript">
        pattern = new RegExp("^[0-9a-zA-Z]+@[0-9a-zA-z]+[\.]{1}[0-9a-zA-Z]+[\.]?[0-9a-zA-Z]+$");

        function valid8email(field, txt)
        {
          with(field)
          {
            //at_pos = value.indexOf('@');
            //dot_pos = value.lastIndexOf('.');

            if(!pattern.test(value)) //at_pos < 1 || (dot_pos - at_pos) < 2)
            {
              alert(txt);
              return false;
            }
            else
            {
              return true;
            }
          }
        }

        function valid8(form)
        {
          with(form)
          {
            if(valid8email(email, "you must enter an email address") == false)
            {
              email.focus();
              return false;
            }
          }
        }
      </script>
    </head>
    <body>
      <form action="#" method="POST" onsubmit="return valid8(this)">

        Email: <input type="text" name="email" size="30" />
        <input type="submit" value="clicky-click" />

    </form>

    <script type="text/javascript">
      alert(pattern.test(""));
    </script>
  </body>
</html>

... script .

javascript :

  • "" -
  • 'undefined' javascript
  • regex , true, script

? .

+3
1

, pattern field.pattern ( HTML5), with(), , . - pattern1, .

with , :)


with :

var pattern = new RegExp("^[0-9a-zA-Z]+@[0-9a-zA-z]+[\.]{1}[0-9a-zA-Z]+[\.]?[0-9a-zA-Z]+$");

function valid8email(field, txt) {
    if (!pattern.test(field.value))
    {
        alert(txt);
        return false;
    }
    else {
        return true;
    }
}

function valid8(form) {
    if (valid8email(form.email, "you must enter an email address") == false) {
        form.email.focus();
        return false;
    }
}

.

+8

Source: https://habr.com/ru/post/1777810/


All Articles