Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript space function

I have a JS code that the function is to validate the form, now what I want to do is add 1 function to prevent space in textbox username with message too, "No space allowed". Here it's my JS code so far :

$().ready(function()
    {
        $("#signupForm").validate(
        {
            rules:
            {
                full_name: "required",
                username: {
                    required: true,
                    minlength: 2
                },
                password: {
                    required: true,
                    minlength: 5
                },
                email: {
                    required: true,
                    email: true
                },
            },
            messages:
            {
                full_name: "Please enter your full name",
                username:
                {
                    required: "Please enter a username",
                    minlength: "Your username must consist of at least 2 characters"
                },

                password:
                {
                    required: "Please provide a password",
                    minlength: "Your password must be at least 5 characters long"
                },

                email: "Please enter a valid email address"
            }
        });
    });

Anyone can give me idea ? Thanks.

like image 237
Naga Botak Avatar asked Dec 20 '22 16:12

Naga Botak


2 Answers

Try this


Add a method called noSpace
jQuery.validator.addMethod("noSpace", function(value, element) {
    return !value.match(/\s/g);
}, "Spaces are not allowed");

Set it as a rule for username

rules: {
    // ...
    username: {
        // ...
        noSpace: true,
        // ...
    },
    // ...

Set a custom message, if you want to override the default message

messages: {
    // ...
    username: {
        // ...
        noSpace: "Username should not contain spaces",
        // ...
    },
like image 154
naveen Avatar answered Jan 01 '23 15:01

naveen


<script type="text/javascript">
function nospaces(t) {
    if(t.value.match(/\s/g)) {
        alert('Sorry, you are not allowed to enter any spaces');
    }
}
</script>

Add following attribute to text input box

onkeyup="nospaces(this)"
like image 40
Mudassir Hasan Avatar answered Jan 01 '23 13:01

Mudassir Hasan