-6

I am trying to detect spaces in the text field using JavaScript, so whenever there is a space in the text field an alert should pop up, but this code is not working, it should work on both text fields.

<!DOCTYPE html>
<html>
    <script type="text/javascript">
        function detectSpace() {
            $returnValue = preg_match('/[^a-z^A-Z^0-9]/', $str, $matches);
            if ($returnValue==1) 
            {
                alert("spaces & symbols are not allowed");
            }
        }
    </script>
    <body onload="detectSpace()">

        <form action="demo_form.asp">
            First name: <input type="text" name="FirstName" value=""><br>
            Last name: <input type="text" name="LastName" value=""><br>
            <input type="submit" value="Submit">
        </form>

        <p>Click the "Submit" button and the form-data will be sent to a page on the server called "demo_form.asp".</p>

    </body>
</html>
James Donnelly
  • 126,410
  • 34
  • 208
  • 218

1 Answers1

4

preg_match is a PHP function and not a JavaScript function - which is made even more obscure by the fact that your back-end code is ASP! PHP and JavaScript are different languages. To match on a string in JavaScript you need to change your code to:

function detectSpace(str) {
    var expression = new RegExp(/\s/);
    var returnValue = expression.test(str);

    if (returnValue === true)
        alert("spaces & symbols are not allowed");
}

With this you'll need to pass in the value you want to test against as an argument in your detectSpace function:

detectSpace("foo");        // No alert fired
detectSpace("foo bar");    // Alert fired

Note that I've also changed your regular expression to /\s/ - this matches white space and will return true if any spaces are found.

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
  • @HassanChaudhry please give more detail. What is not working? Here's a JSFiddle demo showing this working: http://jsfiddle.net/opLap9n9. – James Donnelly Oct 13 '14 at 10:34
  • How do you make it work on the text field? because in the demo there is no HTML, so I want it to detect the space on the text fields the – Hassan Chaudhry Oct 13 '14 at 10:37
  • @HassanChaudhry you'll need to loop through your `input[type="text"]` elements within your `form` and check their value through the `detectSpace` function I've re-written for you above by adding an event listener on the `submit` event of your form. – James Donnelly Oct 13 '14 at 10:39