Not allow a blank character / space in a input form [duplicate]

无人久伴 提交于 2020-02-24 06:24:49

问题


Is it possible to not allow a blank character / space in a input form like below?

<input type="text" value="" maxlength="30" name="email" class="formfield w0">

回答1:


Check this Fiddle. Relevant code:

 $(function() {
        $('#input1').on('keypress', function(e) {
            if (e.which == 32){
                console.log('Space Detected');
                return false;
            }
        });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" id="input1" />



回答2:


Use HTML5's extended input types to apply constraint validation, which will prevent submitting the form with invalid emails in modern browsers:

<input type="email" value="" maxlength="30" name="email" class="formfield w0">

In older browsers, you can detect that the input's type is not "email", as it will default to "text" when a value is considered invalid. I'd recommend blocking the submission of the form, rather than preventing default action of the space key, which could be inadvertently circumvented by pasting or via other input methods.

The following code is an example of this, and should be executed after the document is ready:

var frm = document.getElementById('myform');

if (frm.email.type === 'text') {
    frm.onsubmit = function () {
        if (/\s/.test(frm.email.value)) {
            // Tell your user the field is invalid here, e.g.
            frm.email.className = 'invalid';

            // Prevent form submission
            return false;
        }
    }
}

Working demo: http://jsfiddle.net/hgc7C/

Don't forget that this is not a substitute for server-side form validation.




回答3:


Yes it is possible by using javascript/JQuery.

If you want it for all text boxes, then do as below.

$(function() {
    $('.formfield input[type=text]').on('keypress', function(e) {
        if (e.which == 32)
            return false;
    });
});

If you want it for a specific textbox, then add an id to the textbox input and replace .formfield input[type=text] with #textBoxId



来源:https://stackoverflow.com/questions/19024825/not-allow-a-blank-character-space-in-a-input-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!