Search code examples
javascriptjqueryvalidationemailtrim

How to remove empty space in a input field and re-assign the trim value back


I'm doing a email validation; in the email field, user may put empty space.

So I've decide to $trim the input value and re-assign to input field.

It works normally without any issue, but when I use the space bar couple of time and focus out from the input and turn back, the entered space there in the input field.

Event though I am trimming each of the input - I don't know why the space being with input field.

Any correct approach please?

here is my try:

$('#email').on('input change',function(){
    this.value = $.trim(this.value); //re-assigning trimmed value, but not works when enterning space and focus out. when focus in the space being in the input
    validateEmail.init(this.value);
    if(validateEmail.done()){
        console.log('this is correct');
    }
});

//enter some space and focus out, then come back to input field you can see white spaces in the field

Live Demo


Solution

  • hey i gone through your example..

    i have changed the binding in it and it is working as expected...

    $('#email').on('keyup  change',function(){
    
         var text = $.trim($(this).val() )
         this.value="";      
         this.value=text;
    
        validateEmail.init(this.value);
        if(validateEmail.done()){
            console.log('this is correct');
        }
    });
    

    working example:-http://jsfiddle.net/SG6YN/10/

    now if user will try to paste text with space then it will remove those spaces..

    thanks