2014-10-13 6 views
-5

JavaScript를 사용하여 텍스트 필드의 공백을 감지하려고합니다. 따라서 텍스트 필드에 공백이있을 때마다 경고가 튀어 나오지만이 코드는 작동하지 않고 두 텍스트 모두에서 작동해야합니다. 전지. 백 엔드 코드는 ASP는 사실에 의해 더욱 모호하게한다 -JavaScript 코드가 작동하지 않습니다.

<!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> 
+0

JavaScript에는'preg_match' 함수가 없습니다. – jgillich

+0

"$ str"및 "$ matches"란 무엇이며이 변수를 어디에서 정의합니까? –

+0

또한'$ str'은 정의되지 않았습니다. RegExp와 일치해야하는 것이 무엇인지 모르는 함수를 실행 중입니다. PHP와 JS가 얽혀있는 것처럼 보입니다. – Terry

답변

4

preg_match는 PHP 함수가 아닌 자바 스크립트 기능입니다! PHP와 JavaScript는 서로 다른 언어입니다. 당신이 당신의 코드를 변경해야 자바 스크립트 문자열에 일치 시키려면 :

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

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

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

당신은 당신이 당신의 detectSpace 함수에서 인자로에 대해 테스트 할 값을 전달해야합니다

또한 정규식을 /\s/으로 변경했습니다. 공백과 일치하며 공백이 있으면 true을 반환합니다.

+0

이 작동하지 않습니다. –

+0

@HassanChaudhry 자세히 알려주십시오. 작동하지 않는 것은 무엇입니까? 다음은이 작업을 보여주는 JSFiddle 데모입니다 : http://jsfiddle.net/opLap9n9. –

+0

텍스트 필드에서 어떻게 작동합니까? 데모에서는 HTML이 없으므로 텍스트 필드의 공백을 감지하고 싶습니다.

관련 문제