Jump to content

preg_match to validate form


ontheplains

Recommended Posts

i have never before used the preg_match feature, though i will have to use it for this project.  i am making a madlib on my page and the values that people input into the fields need to meet a certain criteria:    i need to create a function that will check the 4 text inputs. each one must consist of a single word (i.e. no spaces and no extra punctuation such as periods or commas). the first letter may be capitalized (but not other letters). dashes should be allowed after the first letter, provided that you do not end with a dash. each word must be at least 2 characters long.

 

the code for the input goes as such:

 

<p class="centerwindow">
<form name="form1" action="madlib.php">

<p class="centerwindow">I want to do madlib number:<input type="radio" checked="checked" name="madlib" onClick="document.form1.noun3.disabled=false;document.form1.verb1.disabl ed=false" value="1" />1<input type="radio" name="madlib" onClick="document.form1.noun3.disabled=false;document.form1.verb1.disabl ed=false" value="2" />2<input type="radio" name="madlib" onClick="document.form1.noun3.disabled=false;document.form1.verb1.disabl ed=false" value="3" />3<input type="radio" name="madlib" onClick="document.form1.noun3.disabled=true;document.form1.verb1.disable d=true;document.form1.noun3.value='';document.form1.verb1.value='';" value="4" />4

<ol class="centerwindow">
<li> A noun (plural):</li>  <input type="text" name="noun1" />
<li> A noun:</li>  <input type="text" name="noun2" />
<li> A noun:</li>  <input type="text" name="noun3" />
<li> A verb (ending in 'ing'):</li>  <input type="text" name="verb1" />
</ol>

Link to comment
https://forums.phpfreaks.com/topic/50188-preg_match-to-validate-form/
Share on other sites

i'm not sure you want to use preg_match, preg_match matches patterns so if the user input matches the pattern more than once, i.e. 2 words. it wouldn't be caught...

 

eregi may work better for you...

 


//check for input atleast 2 letters + ending in "ing", no spaces, only letters
if(!eregi("^([a-z]{2,})ing$", $test)) {
    echo "test invalid<br>";
}

//check for input atleast 2 letters, no spaces, only letters
if(!eregi("^([a-z]{2,})$", $test)) {
    echo "test invalid<br>";
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.