Javascript form validation not working MeteorJS

时间:2016-07-11 22:08:20

标签: javascript validation meteor meteor-blaze

I am trying to add form validation to my web app by restricting users to a certain length of username and password when they register for the first time.

The HTML code is:

<template name='home'>
    <form class="register">
            <p>Username: <input pattern=".{7, 12}" type="text"  id='username' placeholder='Username' required></p><p id="demo1"></p>
            <br>

            <p>Password: <input pattern=".{7, 12}" type="password" id='password' placeholder='password' required></p><p id="demo2"></p>
            <p><button type="submit" class="btn btn-primary">Create Account</button></p>
             <br>

            <p>Already have an account</p>
            <br>
            <h3><a href='{{pathFor route="login"}}'>Login</a></h3>
        </form>
</template>

The JS code is:

Template.home.events({
  'submit form':function(event){
    event.preventDefault();
      var username = document.getElementById('username').value;
      var password = document.getElementById('password').value;

      if ((username.checkValidity()==true) && (password.checkValidity()==true))
      {
        Accounts.createUser({

          username: username,
          password: password,

        }, function(error){
          if(error){
            alert(error.reason);
            event.target.password.value=''; // Output error if registration fails
          } else {
            Profile.insert({
              name:'',
              hobbies:'',
              description:'',
              currentUser:Meteor.userId(),
              src:'',
              followers:0,
              following:0,
              followedBy:[],
              followingTo:[]
            });   

            Router.go("createProfile"); // Redirect user if registration succeeds
          }    
        });
      }

    else{
      document.getElementById('demo1').innerHTML='Username must contain 7 to 12 characters.';
      document.getElementById('demo2').innerHTML='Password must contain 7 to 12 characters.';
      return false;
    }
  }
});

But on clicking the 'Create Account' button it doesnt links to any other page. Even on entering invalid username and password, the demo1 and demo2 paragraph show no text.

0 个答案:

没有答案
相关问题