0

I'm working on form validation here form validation is not working what might be the issue. Can anyone suggest me.

class Registrationform {
constructor() {
    this.initializeElements();
}
initializeElements () {
    this.demoRegisterWrap = $('.demoRegister-wrap');
    this.registrationForm = $('.registration-form');
    this.username = '#username';
    this.useremail= '#useremail';
    this.userpassword = '#userpassword';
    this.formValidation();
}
formValidation() {
    let submitBtn = this.demoRegisterWrap.find('.submitBtn');
    submitBtn.on('click', e => {
        alert('test');
        e.preventDefault();
        alert('test');
        var text = "";
        if (UserName(this.username)) {
        }
        if (UserEmail(this.useremail)) {
        }
        if (UserPassword(this.userpassword)) {
        }
        return false;
    });
    /*Name input validation*/
    function UserName(username) {
        var message = document.getElementsByClassName("error-message");
        var letters = /^[A-Za-z]+$/;
        if ( username =="" || username.match(letters)) {
        text="";
        message[0].innerHTML = text;
        return true;
        }
        
        else {
        text="Name should contain only letters";
        message[0].innerHTML = text;
        return false;
        }
    }
    

    /*email address input validation*/
    function UserEmail(useremail) {
        var message = document.getElementsByClassName("error-message");
        var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; 
        var atpos = useremail.indexOf("@");
        var dotpos = useremail.lastIndexOf(".");
                
        if ( useremail =="" || useremail.match(mailformat) || atpos > 1 && ( dotpos - atpos > 2 )) {
        text="";
        message[1].innerHTML = text;
        return true;
        }
            
        else {
        text="Wrong email format";
        message[1].innerHTML = text;
        return false;
        }
    }
    
    /*validate password*/
    function UserPassword(userpassword) {
        var message = document.getElementsByClassName("error-message");
        var illegalChars = /[\W_]/; 
        if (illegalChars.test(userpassword)) { 
        text="Password contains illegal characters";
        message[2].innerHTML = text;
        return false;
        }
        else if ( (userpassword.search(/[0-9]+/)==-1) ) {
        text="Password should contain at least one number";
        message[2].innerHTML = text;
        return false;
        }
        else {
        text="";
        message[2].innerHTML = text;
        return true;
        }
    }
}

}

new Registrationform();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="demoRegister-wrap">
<form class="registration-form" novalidate>
  <fieldset>
    <br/>
    <input type="text" id="username" name="name" placeholder="Name" />
    <p class="error-message"></p>
    <input type="text" id="useremail" placeholder="Email" />
    <p class="error-message"></p>
    <input type="password" id="userpassword" pattern=".{8,}" title="8 characters minimum" />
    <p class="error-message"></p>
    <label for="submit"></label>
    <input class="submitBtn" type="submit" value="submit" name="submit" />
  </fieldset>
</form>
   </div>
Teemu
  • 22,918
  • 7
  • 53
  • 106
Husna
  • 1,286
  • 4
  • 19
  • 48
  • 2
    You should use `onsubmit` event of `form`. – Pawan Bishnoi Jun 11 '21 at 04:41
  • @Pawan Bishoni onsubmit If i used `onClick='func();'` in form then some other erroris showing. – Husna Jun 11 '21 at 04:43
  • @ray hatfield Script loading fine if i added alert outside onclick it is coming – Husna Jun 11 '21 at 04:46
  • Your input/button has 2 class declarations. – wazz Jun 11 '21 at 04:49
  • @Husna Follow Pawan's advice, as weird as it sounds, the default action of the submit button is not to submit a form, `e.preventDefault()` won't work, but it will in a form submit handler. – Teemu Jun 11 '21 at 04:49
  • @wazz i removed class="button" alert is working but form not validate – Husna Jun 11 '21 at 04:52
  • @Teemu getting this error `fname is not defined` – Husna Jun 11 '21 at 04:55
  • `if (firstName(fname)) {}` What is `fname`? It is not defined in this scope. – kmoser Jun 11 '21 at 04:56
  • @kmoser `this.fname = '#name';` – Husna Jun 11 '21 at 04:58
  • The entire `formValidation` function is odd. Ex. `email(email)`, a function call which passes the function itself as an argument. You probably meant `email(this.email)` ..? And many other conditions have this same fault. In JS you can't refer to object properties with a pure name in methods, you've to use `this.name`, always. Notice also, that returning from event listeners (specifically attached by `addEventListener`) doesn't do anything, you need to prevent the default action, if that's needed. – Teemu Jun 11 '21 at 04:59
  • @Husna `fname` is not the same as `this.fname`. – kmoser Jun 11 '21 at 05:05
  • A fix to the comment above: "_you probably meant `this.email(email)`_". – Teemu Jun 11 '21 at 05:05
  • Umm ... Actually you're shadowing the prototype `email` and many other methods in `initializeElements` method, where you set ex. `this.email = '#email-id';`. – Teemu Jun 11 '21 at 05:08
  • @Teemu i added like this `if (firstName(this.fname)) {}` now getting this error text is not defined – Husna Jun 11 '21 at 05:11
  • document.querySelectorAll('.demoRegister-wrap')[0].querySelectorAll('.btn-submit')[0].addEventListener('click', () => { alert('click event is triggered'); }); – Guruling Kumbhar Jun 11 '21 at 05:12
  • @GurulingKumbhar Now click is working fine validation is not working i updated my question. – Husna Jun 11 '21 at 05:16
  • You've to sit down and fix all the naming conflicts in the class. When that's done, and if you still have issues with the code, maybe ask a new question, editing this question might invalidate the existing answers. – Teemu Jun 11 '21 at 05:16
  • @Teemu Can you make a snippet of this code. – Husna Jun 11 '21 at 05:18
  • Remove `export` statement from the code in the StackSnippet, then it will run your code. If you're asking me to fix the naming conflicts, I think that's your job, you know the code better, and you know the names you want to use, I would only make a mess out of your code. – Teemu Jun 11 '21 at 05:23
  • @Teemu I updated my question. I'm not asking about naming conventions. I mean working snippet of your code what you're trying to say. I'm getting this error text is not define – Husna Jun 11 '21 at 05:40
  • I've no code for this ... Use Firefox to debug your code, it gives decent human understandable error messages instead of the piglatin the other DevTools are using. – Teemu Jun 11 '21 at 05:51
  • Just as an example, you get "_text is not defined_" error when you've just defined `text`, not very useful message. In FF you get "_assignment to undeclared variable text_", which tells you precisely what is wrong with the code. – Teemu Jun 11 '21 at 06:01

1 Answers1

0

I think you need to remove the return false. Here is a reference that details why. In short, putting the function within another function when the return is present.

If you want the onclick to return false when those functions give you an output that you don't want, then you would want to do it in the HTML, more like this format.

In general, though, I recommend using a fetch{} method because it is much easier and you don't have to worry about the form submitting a blank page which will cause a redirect. Just use this fetch function as the function of the on click.

(data) => fetch('URL to place you are already submitting your form', {
     method: 'POST', 
     body: data
});