Search code examples
pythonjsonajaxflaskwtforms

wtforms validation doesn't work when using AJAX


I have 2 forms on my page - login form and registration form. Now I want to use AJAX to validate those forms so I can see input errors without refreshing the page. I tried to add all that AJAX things to the forms I already had but now it seems like the form validation doesn't work.

routes.py

@users.route('/login', methods=['GET', 'POST'])
def login():
    loginForm = LoginForm()
    registerForm = RegisterForm()

    if request.method == 'POST':
        if registerForm.validate():
            return'wow it works'
        return 'something is wrong'

    return render_template("login.html", loginForm=loginForm, registerForm=registerForm)

P.S. also I'd like to know how to check which form to valide when sending a POST request? Right now I'm just trying to figure out how to fix the problem so I only use registration form. But when I have both how to valide one form and ignore another one?

login.html

const signUpButton = document.getElementById("signUp");
		const signInButton = document.getElementById("signIn");
		const container = document.getElementById("container");

		signUpButton.addEventListener('click', () => {
			container.classList.add("right-panel-active");
		});

		signInButton.addEventListener('click', () => {
			container.classList.remove("right-panel-active");
		});



		const fields = {
			username: {
				input: document.getElementById('username'),
				error: document.getElementById('username-error')
			},

			email: {
				input: document.getElementById('email'),
				error: document.getElementById('email-error')
			},

			password: {
				input: document.getElementById('password'),
				error: document.getElementById('password-error')
			},

			confirm_password: {
				input: document.getElementById('confirm_password'),
				error: document.getElementById('confirm-password-error')
			}

		} 

		var regForm = document.getElementById('register-form');
		regForm.addEventListener('submit', async (e) => {
			e.preventDefault();

			const response = await fetch('/login', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json'
				},

				body: JSON.stringify({
					username: fields.username.input.value,
					email: fields.email.input.value,
					password: fields.password.input.value,
					confirm_password: fields.confirm_password.input.value
				})
			});

			if (response.ok) {
				alert('yes');
				console.log(response);
			}
			else {
				const errors = await response.json();
				Object.key(errors).forEach((key) => {
					fields[key].input.classList.add('input-invalid');
					fields[key].error.innerHTML = errors[key][0];
				});
			}
		});
<div class="form-container sign-up-container">
  <form id="register-form" action="" method="POST">
    {{ registerForm.hidden_tag() }}

    <h1>Create an account</h1>

    <fieldset class="uk-fieldset">
      <div class="uk-margin form-group">
        {% if registerForm.username.errors %} {{ registerForm.username(class="uk-input input-invalid") }}

        <div class="input-erros" id="username-error">
          {% for error in registerForm.username.errors %}
          <span>{{ error }}</span> {% endfor %}
        </div>

        {% else %} {{ registerForm.username(class="uk-input") }} {% endif %}
      </div>

      <div class="uk-margin form-group" id="email-error">
        {% if registerForm.email.errors %} {{ registerForm.email(class="uk-input input-invalid") }}

        <div class="input-erros">
          {% for error in registerForm.email.errors %}
          <span>{{ error }}</span> {% endfor %}
        </div>

        {% else %} {{ registerForm.email(class="uk-input") }} {% endif %}
      </div>

      <div class="uk-margin form-group" id="password-error">
        {% if registerForm.password.errors %} {{ registerForm.password(class="uk-input input-invalid") }}

        <div class="input-erros">
          {% for error in registerForm.password.errors %}
          <span>{{ error }}</span> {% endfor %}
        </div>

        {% else %} {{ registerForm.password(class="uk-input") }} {% endif %}
      </div>

      <div class="uk-margin form-group" id="confirm-password-error">
        {% if registerForm.confirm_password.errors %} {{ registerForm.confirm_password(class="uk-input input-invalid") }}

        <div class="input-errors">
          {% for error in registerForm.confirm_password.errors %}
          <span>{{ error }}</span> {% endfor %}
        </div>

        {% else %} {{ registerForm.confirm_password(class="uk-input") }} {% endif %}
      </div>

      <div class="uk-margin form-group">

      </div>
    </fieldset>

    <button class="form-button">Create an account</button>
  </form>
</div>


<div class="form-container sign-in-container">
  <form action="#">
    <h1>Sign In</h1>

    <fieldset class="uk-fieldset">
      <div class="uk-margin">
        {{ loginForm.usernameLogin(class="uk-input") }}
      </div>

      <div class="uk-margin">
        {{ loginForm.passwordLogin(class="uk-input") }}
      </div>

      <div class="uk-margin">
        {{ loginForm.submit(class="form-button") }}
      </div>
    </fieldset>
  </form>
</div>


<div class="overlay-container">
  <div class="overlay">

    <div class="overlay-panel overlay-left">
      <h1>Don't have an account yet?</h1>
      <!-- <p>just sign in</p> -->
      <button class="ghost form-button" id="signUp">Create an account</button>
    </div>

    <div class="overlay-panel overlay-right">
      <h1>Already have an account?</h1>
      <!-- <p>become a part of the community</p> -->
      <button class="ghost form-button" id="signIn">Sign In</button>
    </div>

  </div>
</div>

forms.py

class RegisterForm(FlaskForm):
    username = StringField('username',
                            validators=[
                                DataRequired("username is required"), 
                                Length(min=5, 
                                        max=15, 
                                        message="must be between 5 and 15 characters")
                            ], 
                            render_kw={"placeholder": "username"})

    email = StringField('e-mail',
                            validators=[
                                DataRequired("e-mail is required"), 
                                Email(message="probably not e-mail")
                            ],
                            render_kw={"placeholder": "e-mail"})

    password = PasswordField('password',
                                validators=[DataRequired("password is required")], 
                                render_kw={"placeholder": "password"})

    confirm_password = PasswordField('confirm password',
                                        validators=[
                                            DataRequired("confirm password"), 
                                            EqualTo('password')
                                        ], 
                                        render_kw={"placeholder": "confirm password"})


    def validate_username(self, username):
        pass

    def validate_email(self, email):
        pass

    def validate_password(self, password):
        pswd = password.data
        flag = 0

        while True:
            if (len(pswd)<8):
                flag = -1
                break

            elif not re.search("[a-z]", pswd):
                flag = -1
                break

            elif not re.search("[A-Z]", pswd):
                flag = -1
                break

            elif not re.search("[0-9]", pswd):
                flag = -1
                break

            else:
                flag = 0
                break

        if flag == -1:
            raise ValidationError('the password is too simple')

When I submit the registration form it seems like only DataRequired validator works. Because I can put anything into email and password and I still get that 'yes' alert like the response is ok.


Solution

  • Validating a JSON request using WTForms is slightly different to handling a normal, urlencoded form request.

    Here's simple example that uses the RegisterForm from the question.

    # imports here
    ...
    import wtforms_json
    
    # Initialise wtforms_json
    wtforms_json.init()
    
    app = Flask(__name__) 
    app.config['SECRET_KEY'] = b'secret'  
    
    
    @app.route('/login', methods=['POST'])  
    def login():
    
        # Get the JSON data from the request.
        formdata = request.get_json()
        # Create the form using the from_json constructor
        registerForm = RegisterForm.from_json(formdata=formdata)
        # Return a dict, which will automatically be serialised as JSON.
        if registerForm.validate_on_submit():
            return {'result': 'success'}
        return registerForm.errors 
    
    app.run()
    

    Notable features:

    • Use the wtforms_json package to enable JSON andling in wtforms forms.
      • wtforms_json.init() must be called to add JSON features to the Form class
    • The route handler returns dicts after the form has been validated; Flask will automatically convert these to JSON responses. I find it's best to render forms in a GET route handler that renders the entire HTML page, but have separate handlers to handle requests from javascript, when only JSON-serialised data is being transferred.

    If this data is sent to the app, error validation is as expected:

    $ cat register.json 
    {
        "username": "Tharg",
        "email": "Banana",
        "password": "red",
        "confirm_password": "blue",
        "csrf_token": "secret"
    }
    $ curl -X POST -H "Content-Type: application/json" -d @register.json http://localhost:5000/login 
    {"confirm_password":["Field must be equal to password."],"csrf_token":["The CSRF token is missing."],"email":["probably not e-mail"],"password":["the password is too simple"]}