user2932587
user2932587

Reputation:

Not Allowing Whitespace With Javascript Validation

I am working on a web form that must be validated on submit. I have a field for a first name that must follow two rules when validated, the name must have at least 3 letters and there can be no spaces between any of the characters. I have gotten it to display an error message when the name is too short, but I can't figure out how to not allow whitespace.

How can I validate this so that there are no spaces between any characters using javascript?

Here is my code so far:

<html>
    <head>
        <title>Project 5</title>
    </head>

    <body>
        <form name="myForm" id="myForm" onsubmit="return validateForm()">
            First Name: <input type="text" id="name"> <br>
            Age: <input type="text" id="age"> <br>
            Street Address: <input type="text" id="address"> <br>
            State: <select>
                <option value="la">LA</option>
                <option value="tx">TX</option>
                <option value="ok">OK</option>
                <option value="mi">MI</option>
                <option value="az">AZ</option>
            </select> <br>
            Login Password: <input type="password" id="password"> <br>
            <input type="submit" value="Submit"> <br>
        </form>

        <script type="text/javascript">
            function validateForm() {
                return checkName();
            }

            function checkName() {
                var x = document.myForm;
                var input = x.name.value;
                if(input.length < 3) {
                    alert("Please enter a name with at least 3 letters");
                    return false;
                }
                else if(input.length >= 3) {

                }
            }

        </script>

    </body>
</html>

Upvotes: 3

Views: 30097

Answers (3)

loyola
loyola

Reputation: 4062

there is an option to remove white space of all the text by just using single line of code from Javascript.

text=text.split(' ').join('');  // this will remove all the white space in your text.

Upvotes: 4

Krzysztof Jabłoński
Krzysztof Jabłoński

Reputation: 1941

I'd recommend using a regex for form input validation. Check examples below:

shouldFailTooShort  = 'ts';
shouldFailSpace  = 'has space';
shouldPass  = 'no-spaces';

validationRule = /^\S{3,}$/;
validationRule.test(shouldFailTooShort) === false;
validationRule.test(shouldFailSpace) === false;
validationRule.test(shouldPass) === true;

Using regular expressions one can have all validation against a field performed in one regular expression check, like presented above. For usability however I'd recommend having one rule for each validation requirement. Then different validation rules can produce different messages and user does not get confused having to read one and always same message.

Have a peek on my favourite regular expression reference.

Edit: As requested in comment, herein I present my proposal of deploying the solution. I suggest not using alert function in production, but display the message on the page itself, e.g. in a span element.

HTML:

<form name="myForm" id="myForm" onsubmit="return validateForm();">
    First Name: <input type="text" id="name" /> <br />
    <span id="nameErrMsg" class="error"></span> <br />
    <!-- ... all your other stuff ... -->
</form>
<button id="validateTestButton" value="Validate now" onclick="validateForm();">Validate now</button>

JavaScript:

validateForm = function () {
    return checkName();
}

function checkName() {
    var x = document.myForm;
    var input = x.name.value;
    var errMsgHolder = document.getElementById('nameErrMsg');
    if (input.length < 3) {
        errMsgHolder.innerHTML =
            'Please enter a name with at least 3 letters';
        return false;
    } else if (!(/^\S{3,}$/.test(input))) {
        errMsgHolder.innerHTML =
            'Name cannot contain whitespace';
        return false;
    } else {
        errMsgHolder.innerHTML = '';
        return undefined;
    }
}

Check live example in jsfiddle.

Upvotes: 2

Jared Smith
Jared Smith

Reputation: 21926

for (var i=0, len = string.length; i<len; ++i) {
    if (string.charAt(i) === ' ') {
        alert('Name cannot have spaces!');
        break;
    }
}

Upvotes: 1

Related Questions