User is able to enter blank spaces as input in input paramater in js file

471 Views Asked by At

I want to apply validation where user cannot input name starting from blank space, in my present code whe user is giving value using spacebar its successfully entering blank value. I want to apply validation where user can use space but not in the beginning

if($('#workspaceNameUpdate').val().trim().length == 0 && $('#workspaceNameUpdate').val() === "") {  
 $('#workspaceNameUpdate').addClass('error');
 $('#workspaceNameUpdateError').removeClass('hidden');
}

I am using trim class but its not working its not entering into the error block!

3

There are 3 best solutions below

1
Mishika Dhar On BEST ANSWER

I think there should be || instead of &&

$('#workspaceNameUpdate').val().trim().length == 0

because the first part is trimming and then checking the length - which is right

but the second part $('#workspaceNameUpdate').val() === "" - is comparing that value and " " != ""

solution - I think the first check will handle everything and there is no need of second check

0
Neha Soni On

Use this regex when you want to validate the input-

/^(?![\s-])[\w\s-]+$/

Below is two working examples to check whether space is at the beginning or middle or end.

  1. On character input -

function validate(input) {
  console.log(/^(?![\s-])[\w\s-]+$/.test(input));
}
<input oninput="validate(this.value)" label="enter name">

  1. Custom input-

function validate(input) {
   console.log(/^(?![\s-])[\w\s-]+$/.test(input));
}

// two blank space at the beginning (fail)
validate("   firstname");
// one blank space at the beginning (fail)
validate(" firstname");
// blank space at the middle (pass)
validate("firstname   lastname");
// blank space at the last (pass)
validate("firstname   ");

0
CandleCoder On

You can add a regex check like this -

if(/^\s/.test(yourInput.value))