3gwebtrain
3gwebtrain

Reputation: 15309

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

Upvotes: 4

Views: 7583

Answers (2)

Devendra Soni
Devendra Soni

Reputation: 1934

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

Upvotes: 1

Roshan
Roshan

Reputation: 2184

Restrict user to entering space in the field

$('#email').keydown(function(e) {
        if (e.keyCode == 32) // 32 is the ASCII value for a space
            e.preventDefault();
    });

But if user copy and paste whitespace containing text then it doesnot work. So add following code on your onChange function

$('#email').on('input change',function(){
    $(this).val($(this).val().replace(/\s+/g, ''));
    validateEmail.init(this.value);
    if(validateEmail.done()){
        console.log('this is correct');
    }
});

The working fiddle is here

Upvotes: 1

Related Questions