1

I have the following to disallow spaces

function nospaces(t){

    if(t.value.match(/\s/g)){

        alert('Username Cannot Have Spaces or Full Stops');

        t.value=t.value.replace(/\s/g,'');

    }

}

HTML

<input type="text" name="username" value="" onkeyup="nospaces(this)"/>

It works well for spaces but how can I also disallow full stops as well?

3 Answers 3

3

Try this

    function nospaces(t){
        if(t.value.match(/\s|\./g)){
            alert('Username Cannot Have Spaces or Full Stops');
            t.value=t.value.replace(/\s/g,'');
        }
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks this works well. I just changed the last line to t.value=t.value.replace(/\s|\./g,'');
I tried but not snough reputation. Once I get a good rep I will come back and vote up
oh forgot abt that. I have been there once :)
2

Below is the sample html and javscript you just wanted to add /./g for checking for .

<html>
<input type="text" name="username" value="" onkeyup="nospaces(this)"/>
<script>
function nospaces(t){

    if( t.value.match(/\s/g) || t.value.match(/\./g)  ){

        alert('Username Cannot Have Spaces or Full Stops');

        t.value= (t.value.replace(/\s/g,'') .replace(/\./g,''));

    }

}
</script>
</html>

Comments

1

If not its not necessary to use regex you can use

if(value.indexOf('.') != -1) {
    alert("dots not allowed");
}

or if required

if(value.match(/\./g) != null) {
    alert("Dots not allowed");
}

Comments

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.