Javascript:如何验证一个条目是否为空但同时验证它没有插入空格?

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<html>

<body>

<form id="api_crud_form" name="api_crud_form" action="https://www.google.es">

Name: <input type="text" name="name" id="name"><br>

    <input type="submit" value="Send">

</form>

</body>

</html>


<script type="text/javascript">

$(document).ready(function () {

 $('#api_crud_form').on('submit', function (event) {

            event.preventDefault();

            if ($('#name').val() == '') {

                alert("enter name");

            } 

            else{

              alert("the data was sent");

            }

    });

  });


</script>

这是一个例子

如果该字段为空,则这是一个有效示例,但如果插入空格则无效

正如您在发送空格的示例中看到的


DIEA
浏览 79回答 2
2回答

红糖糍粑

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><html><body><form id="api_crud_form" name="api_crud_form" action="https://www.google.es">Name: <input type="text" name="name" id="name"><br>&nbsp; &nbsp; <input type="submit" value="Send"></form></body></html><script type="text/javascript">$(document).ready(function () {&nbsp;$('#api_crud_form').on('submit', function (event) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; event.preventDefault();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if ($('#name').val().trim() == '') {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert("enter name");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert("the data was sent");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; });</script>

FFIVE

使用trim():if&nbsp;($('#name').val().trim()&nbsp;==&nbsp;'')&nbsp;{
打开App,查看更多内容
随时随地看视频慕课网APP