jqueryfocusformvalidation-plugin

I want an alert box to be displayed and after that my input field to stay on focus when it's value is empty


I am doing modal form validation and on button click, i want an alert message to be displayed and my unfilled input field to stay on focus until it is filled. But that doesn't work. I created a function: submitForm() but when i click the submit button it displays an alert message and refreshes the page but doesn't focus on the input field

Here is my submitForm function:

function submitForm(){
 var reg = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
    var name = $('#Input1_username').val();
    var email = $('#Input2_email').val();
    var password = $('#Input3_password').val();
    var confirmPassword = $('#Input4_Cpassword').val();
    if(name.trim() == '' ){
        alert('Please enter your name.');
        $('#Input1_username').focus();
        return false;
    }else if(email.trim() == '' ){
        alert('Please enter your email.');
        $('#Input2_email').focus();
        return false;
    }else if(email.trim() != '' && !reg.test(email)){
        alert('Please enter valid email.');
        $('#Input2_email').focus();
        return false;
    }else if(password.trim() == '' ){
        alert('Please enter your password.');
        $('#Input3_password').focus();
        return false;
    }else if(confirmPassword.trim() == '' ){
        alert('Please confirm your password.');
        $('#Input4_Cpassword').focus();
        return false;
    }else if(confirmPassword != password){
        alert('Please confirm your password 2.');
        $('#Input4_Cpassword').focus();
        return false;
    }
    
    else{ alert ("Try Again");}

}

Solution

  • To solve your problem immediately, change your inline code from <form onsubmit="submitForm()" or <button onclick="submitForm()" to <form onsubmit="return submitForm()"

    However I strongly advice you

    Add required and delete all the parts that refer to empty field, leaving only the email and the confirm password tests

    Alternatively only alert once and focus only once

    In any case use preventDefault to stop the submission - the reason your script does not focus is because the page is reloaded because you did not stop the form from submitting

    $("#formId").on("submit", (e) => {
      var reg = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
      const name = $('#Input1_username').val();
      const email = $('#Input2_email').val();
      const password = $('#Input3_password').val();
      const confirmPassword = $('#Input4_Cpassword').val();
      const errors = [];
      let focusId;
      if (name.trim() == '') {
        focusId = 'Input1_username';
        errors.push('Please enter your name.');
      } else if (email.trim() == '') {
        if (errors.length === 0) focusId = 'Input2_email';
        console.log(focusId);
        errors.push('Please enter your email.');
      } else if (!reg.test(email)) {
        if (errors.length === 0) focusId = 'Input2_email';
        console.log(focusId);
        errors.push('Please enter valid email.');
      } else if (password.trim() == '') {
        if (errors.length === 0) focusId = 'Input3_password';
        errors.push('Please enter your password.');
      } else if (confirmPassword.trim() == '') {
        if (errors.length === 0) focusId = 'Input4_Cpassword';
        errors.push('Please confirm your password.');
      } else if (confirmPassword != password) {
        if (errors.length === 0) focusId = 'Input4_Cpassword';
        errors.push('Please confirm your password 2.');
      }
      if (errors.length > 0) {
        alert(errors.join('\n'));
        console.log(focusId);
        $(`#${focusId}`).focus();
        e.preventDefault(); // stop submission
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form id="formId">
      <label><input type="text" id="Input1_username" name="Input1_username" /> User name</label><br/>
      <label><input type="text" id="Input2_email" name="Input2_email" /> Email</label><br/>
      <label><input type="password" id="Input3_password" name="Input3_password" /> Password</label><br/>
      <label><input type="password" id="Input4_Cpassword" name="Input4_Cpassword" /> Check password</label><br/>
      <button type="submit">Submit</button>
    </form>