Jump to content

Recommended Posts

Hi,

 

I am trying to validate a field so the user must enter some text and also only be allowed to enter alphanumeric characters, but it doesn't work.

 

Any ideas what I have wrong?

 

I have this code:

 

function validateForm()
{
var x=document.forms["Form"]["inputtext"].value;
if (x==null || x=="")
  {
  alert("You must enter some text!");
  return false;
  }
  
if (/[^0-9a-bA-B\s]/gi.test(inputtext.value))
{
alert ("Only alphanumeric characters and spaces are valid in this field");
fieldname.value = "";
fieldname.focus();
return false;
} 

}  

Link to comment
https://forums.phpfreaks.com/topic/268235-validation-issue/
Share on other sites

Thanks.

 

I now have this, but it still doesn't work :(

 

function validateForm()
{
var x=document.forms["Form"]["inputtext"].value;
if (x==null || x=="")
  {
  alert("You must enter some text!");
  return false;
  }
  
if (/[^0-9a-zA-Z\s]/gi.Form(inputtext.value))
{
alert ("Only alphanumeric characters and spaces are valid in this field");
inputtext.value = "";
inputtext.focus();
return false;
} 

}

 

 

Link to comment
https://forums.phpfreaks.com/topic/268235-validation-issue/#findComment-1377053
Share on other sites

The carat (^) you entered at the start means that it should match any characters OTHER than the ones listed. Remove the carat.

 

I think that was his intention; disapprove the input if it contains any character OTHER than what is in the regex.

 

 

Where are you calling this function? You have to call it onsubmit or sooner.

Link to comment
https://forums.phpfreaks.com/topic/268235-validation-issue/#findComment-1377219
Share on other sites

You also can't make use of the modifiers with the shorthand notation. You need to manually create a new RegExp object and pass them in as the second argument, then use that within your condition.

 

Edit

 

Actually, I'm completely wrong here! Ignore that, I always thought it was the case.

Link to comment
https://forums.phpfreaks.com/topic/268235-validation-issue/#findComment-1378280
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.