0

I have a textbox which accepts 4 alphanumeric characters and spaces. For ex: 34 56 should be valid 6789 is also valid.

$('#empIdtextbox1').on('blur', function () {
    var val = $(this).val();
    $(this).val(val.replace(" ", ''));
});

and

[MaxLength(4, ErrorMessage = "The emp code cannot be more than 4 alphanumeric characters")]

public string EmpId{ get; set; }

However when I type 34 56, It replaces the spaces but displays The emp code cannot be more than 4 alphanumeric characters.

Any input on this will be helpful

  • 3
    Try making that `keyup` rather than `blur`. That should strip the spaces out as you type. – zack.lore Nov 17 '14 at 14:36
  • 1
    I don't know much about dataannotations but I can assume that the validation's probably done before you are able to change the value. – Noy Nov 17 '14 at 14:36
  • instead of using 'blur' would it work with 'focusout' event instead. I think 'focusout' happens before; so it might work. Source http://www.w3.org/TR/DOM-Level-3-Events/#event-type-focusout – jyrkim Nov 17 '14 at 14:45
  • @zack.lore key up will make sure that space is not in that data. But I want it to allow adding space after the second character – test acc acc Nov 17 '14 at 16:35
  • Thanks @jyrkim focusout seems to work just like blur. But it still displays the error till i come out of that textbox- Which is not right. Is there a way to trim it only when the space is after the second character. – test acc acc Nov 17 '14 at 16:42
  • @NoyGabay I think so. Is there a way to do validation after trimming data? – test acc acc Nov 17 '14 at 16:52
  • You could try a custom validation attribute [example here](http://stackoverflow.com/questions/16100300/asp-net-mvc-custom-validation-by-dataannotation). You could just check for the position of the space and the length of the input in a way that suits your needs. – zack.lore Nov 17 '14 at 16:53
  • @testaccacc I guess the keyup would be then the most practical like zack.lore and Noy Gabay recommend. However, I think the data annotations could work if you allowed strings of length 5, and after blur did the trimming to 4 characters – jyrkim Nov 18 '14 at 12:04

0 Answers0