0

I have the following code and I need to convert it to Angular Js..also I'd like to stop the user from entering a space only at the start (can't input space bar before any text)

<input type="text" name="firstname" runat="server" onkeypress="return AvoidSpace()">

 function AvoidSpace() { 
         var x=document.forms["firs`enter code here`tname"].value;
                            if (event.keyCode == 32 ) { 
                                    event.returnValue = false; 
                                    return false; 
                            } 
                    } 

2 Answers 2

1

in order to filter space key press you can use the pattern feature of input type=text.

html5 only: https://www.w3.org/wiki/HTML/Elements/input/text

angularjs: https://docs.angularjs.org/api/ng/input/input[text]

<input ng-pattern="[^\s+]" type="text" name="firstname">

update:

you can use the directive ngKeypress:

<input ng-pattern="[^\s+]" type="text" name="firstname" ng-keyup="checkinput($event)">

controller:

$scope.checkinput = function(keyevt){
  if (keyevt.keyCode === 32 ) { 
     keyevt.returnValue = false; 
     return false;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

IIRC pattern only trigger form validation but it doesn't stop the user from entering the text.
Thank you for your comment, I decided to use angular js because I already have a pattern I'm using which is : "^[^&<>\"'/]*$ and when I tried to combine that /s for whitespace with mine it didn't work.
in order to add the space rule to your pattern you should use ^[^&<>\"'\/\s]*$. I tested it on regeex101.com and it functions well. For the previous update thanks to @Icycool suggestion.
0
<input type="text" name="firstname" runat="server" ng-keypress="AvoidSpace()">

function in controller

$scope.AvoidSpace = function AvoidSpace() { 
         var x=document.forms["firs`enter code here`tname"].value;
                            if (event.keyCode == 32 ) { 
                                    event.returnValue = false; 
                                    return false; 
                            } 
                    } 

1 Comment

You might have to pass in $event from the view for it to be available in the function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.