Search code examples
javascriptinputcontactsminimum

JavaScript script to validate minimum words entered in input


I really don't know how to do this. So I need a JavaScript script that'd look at the contact form field (question name) and make sure it has more than one word before submitting it.

<input type="text" name="question[name]" id="question_name">

I really searched a lot, found some solutions but non of them really worked.

Can you help me?


Solution

  • <input type="text" name="question[name]" id="question_name" onblur="this.value.split(' ').length < 2 ? alert('you need more words here') : '';" />
    

    jsfiddle


    Edit to improve it:

    HTML code:

    <p>
        <input type="text" name="question[name]" id="question_name" onblur="CheckErrors.Name(this);" />
        <span class="error"></span>
    </p>
    

    JS code:

    var CheckErrors = {
    
        Config: {
            Error_Strings: {
                Name: 'you need more words here',
                Email: 'the email looks invalid'
                //, ....
            }
        },
    
        Name: function(element){
            try{
                var error_target = element.nextElementSibling;
                if( element.value.split(' ').length < 2 ){
                    error_target.textContent = this.Config.Error_Strings.Name;
                }
                else{
                    error_target.textContent = '';
                }
            }
            catch(e){
                console.log(e.stack);
            }
        }
    
        //, Email: function(element){}....
    };