-1

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!

Michael M.
  • 10,486
  • 9
  • 18
  • 34
  • Why you don't simply trim it ? blank spaces at the begining/end is usually a user mistake, and you can safely discard them – Lk77 Dec 20 '22 at 10:47
  • No i cannot simply trim that how can i use this as a validation – Kritika Rohilla Dec 20 '22 at 10:59
  • You can do something like `str.trim().length == str.length` – Lk77 Dec 20 '22 at 11:04
  • No its not working if($('#workspaceNameUpdate').val().trim().length == $('#workspaceNameUpdate').val().length && $('#workspaceNameUpdate').val() === "") Are you saying like this ? – Kritika Rohilla Dec 20 '22 at 11:08
  • no i don't mean like this, use `str.trim().length == str.length` to validate that the string does not contain blank spaces, if you need to display an error message when the validation fail, you can use something like `str.trim().length != str.length`. And if you have extra cases you need to use OR (`||`) not AND (`&&`) – Lk77 Dec 20 '22 at 13:01
  • [Java is not JavaScript!](https://stackoverflow.com/questions/245062/whats-the-difference-between-javascript-and-java) – Michael M. Dec 20 '22 at 16:21

3 Answers3

2

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

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   ");
Neha Soni
  • 3,935
  • 2
  • 10
  • 32
0

You can add a regex check like this -

if(/^\s/.test(yourInput.value))
CandleCoder
  • 1,387
  • 4
  • 21
  • 45